C++ ยท Chapter 31 of 49

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.

Example 1 (cpp)
class Car {
public:
    std::string brand;
    void honk() { std::cout << brand << " says Beep!"; }
};
int main() {
    Car c;
    c.brand = "Toyota";
    c.honk();
}
Output
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.
๐Ÿ’ก Note: Group related public methods first, then private implementation details, for a readable class layout.

๐Ÿ“ Quick Quiz

1. What keyword defines a class?

2. By default, class members are:

3. How do you access a public member of object c?