Classes and Objects
A class is a blueprint that bundles data (attributes) and behaviour (methods) together. An object is a specific instance created from that blueprint.
Defining a Class
A class groups related data and functions under one name. By convention, data is kept private and accessed through public methods, a principle you'll explore fully in the Encapsulation lesson.
class Student {
public:
std::string name;
int age;
void introduce() {
std::cout << "Hi, I'm " << name << ", age " << age << std::endl;
}
};
int main() {
Student s1;
s1.name = "Kagiso";
s1.age = 21;
s1.introduce();
return 0;
}
Access Specifiers
C++ classes support three access levels that control what code outside the class can touch.
- public — accessible from anywhere the object is visible.
- private — accessible only from within the class itself (the default for classes).
- protected — like private, but also accessible to derived (subclass) classes.
Common Mistakes
- Forgetting that class members are
privateby default, so an unmarked member cannot be accessed from outside without an explicitpublic:label. - Confusing a class (the blueprint) with an object (a specific instance created from it).
- Accessing an object's attributes directly everywhere instead of through methods, defeating the purpose of encapsulation.
- Naming a member function the same as the class itself outside of constructor context, causing confusing errors.
Professional Tip
In C++, struct and class are almost identical — the only difference is that struct members default to public while class members default to private. Convention uses struct for simple data bundles and class for types with behaviour.
Your Turn
Create a class called Book with public attributes for title, author, and price. Create two Book objects in main(), set their attributes, and print a formatted description of each.
Mini Quiz
By default, what is the access level of members in a C++ class (declared with the class keyword)?
class are private by default, which is the opposite default to struct, where members are public by default.