C++ · Beginner level

Beginner level · Module 4: References, Pointers and First Classes · Lesson 2 of 3

Your First C++ Class

Define a class with private data and public member functions, and create objects from it.

In this lesson you will

  • Write a class with private data members and public member functions
  • Create objects and call member functions

Key concepts

classpublic and privatemember functionobject

The lesson

A class bundles data and the functions that work on it. Data members are usually private so only the class's own functions can change them; member functions that other code uses are public.

Member functions that only read data should be marked const: double level() const;. The compiler then prevents them from changing the object and allows them to be called on const objects.

Each object has its own copy of the data members. Two WaterPoint objects keep separate readings, just as two forms of the same printed template hold different answers.

Step by step

  1. Write a class WaterPoint with private name and reading members.
  2. Add public member functions to record and get a reading.
  3. Mark the getter const.
  4. Create two objects and show they hold separate data.

Practice activity

Write a Student class with a name and marks, and a const member function average().

Expected result: Several Student objects report their own averages correctly.

Check your understanding

  1. Why mark a member function const?

    Show answer

    It promises not to change the object and can be called on const objects.

  2. Who can access private data members?

    Show answer

    Only the class's own member functions (and friends).

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.