C++ Classes and Objects
A class is defined with the `class` keyword, containing member variables (attributes) and member functions (methods). You create objects from a class the same way you declare a regular variable.
By default, class members are private, meaning they can't be accessed directly from outside โ you typically expose behaviour through public methods.
Defining a class
`class Car { public: std::string brand; void honk() { std::cout << "Beep!"; } };` defines attributes and methods together.
Creating objects
`Car myCar; myCar.brand = "Toyota"; myCar.honk();` creates an object and uses dot notation to access its public members.
class Car {
public:
std::string brand;
void honk() { std::cout << brand << " says Beep!"; }
};
int main() {
Car c;
c.brand = "Toyota";
c.honk();
}Toyota says Beep!The object c is created from the Car class and its members are set/used with dot notation.
Key points
- class defines a blueprint with attributes and methods.
- Members default to private in a class (public in a struct).
- Objects are created like normal variables of the class type.
- Dot notation accesses public members of an object.
