C++
Summary - Classes
Combine member variables, functions and access modifiers to write a User class.
Summary - Classes
In this section you saw the fundamentals of C++ classes. A class is defined with the class keyword and needs a semicolon after the body. Member variables hold data; member functions hold behavior.
The this pointer refers to the calling object; it resolves name clashes and enables chaining. Access modifiers (public, private, protected) control external access to members and enable encapsulation. Now we will consolidate all of this with a task.
Exercise Define the Light class and use it
Define a Light class. int watts; member (private), under public: add void setWatts(int watts) { this->watts = watts; } and int getWatts() { return watts; }. In main create an instance, call setWatts(60) and print the result of getWatts() with std::cout.
Show example solution
#include <iostream>
class Light {
int watts;
public:
void setWatts(int watts) {
this->watts = watts;
}
int getWatts() {
return watts;
}
};
int main() {
Light bulb;
bulb.setWatts(60);
std::cout << bulb.getWatts();
return 0;
}
Exercise Add a member function to the Light class
Take the Light class above and add a new member function void describe(). Its body should print std::cout << watts << " watts";. In main create an instance, call setWatts(40) and describe().
Show example solution
#include <iostream>
class Light {
int watts;
public:
void setWatts(int watts) {
this->watts = watts;
}
int getWatts() {
return watts;
}
void describe() {
std::cout << watts << " watts";
}
};
int main() {
Light bulb;
bulb.setWatts(40);
bulb.describe();
return 0;
}
What's next?
You learned the fundamentals of classes: definition, member variables, member functions, the this pointer and access modifiers. When you create an object, initializing members is still manual; this is tedious and error-prone.
In the next section you will learn to initialize objects automatically with a constructor. A constructor is a special member function with the same name as its class, called automatically when an object is declared. This way initial values live in one place.
Test yourself
-
In class Light { int watts; public: int getWatts(); };, what is the access level of watts?
class Light { int watts; public: int getWatts(); };
- private
- public
- protected
- No access modifier
Show answer
private — Members without a modifier are treated as private.
-
Complete the assignment with this
void setWatts(int watts) { ____->watts = watts; }
Show answer
void setWatts(int watts) { this->watts = watts; }
Next lesson: Constructor