10.3 — Classes: objects with behaviour

📘 Chapter 10⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Data + actions#

A class is like a struct, but it also holds functions that work on its data. These are called member functions.

C++▶ Run
class Counter{public:    void increase()    {        ++m_count;    }     int get() const    {        return m_count;    } private:    int m_count { 0 };}; int main(){    Counter clicks {};    clicks.increase();    clicks.increase();    std::cout << clicks.get();   // 2    return 0;}

Words to know#

  • A class is the blueprint (like the plan for a house).
  • An object is one thing made from it (like an actual house). clicks is an object.
  • public: = anyone can use these.
  • private: = only the class's own functions can use these.
Tip

Many people start private member names with m_ (for "member"). It makes them easy to spot.

The const after get()#

int get() const promises that get won't change the object. Mark every member function that only reads data as const.

struct or class?#

They're almost the same in C++. By habit:

  • Use a struct for simple bundles of data with everything public.
  • Use a class when the data has rules to protect, with private members and public functions.
Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.