Classes, constructors and destructors

Bundling data with behaviour, controlling how objects are created, copied and destroyed, and letting the compiler write comparisons.

What you'll learn
  • Tell struct and class apart, and use access control
  • Write constructors with member initialiser lists, and copy constructors
  • Use a destructor to release resources (RAII), and overload operators

18structs.cpp groups two ints with a function that prints them:

struct Point {
    int x;
    int y;
    void print() { std::cout << "x= " << x << '\n' << "y= " << y << '\n'; }
};

19classes.cpp writes the same thing with class. The only difference between the two keywords is the default access: members of a struct are public, members of a class are private. With x and y private, the outside world must go through set_x_y, which is the place to enforce rules later (for example that a point stays on screen).

Constructors

Point() = default;
Point(int new_x, int new_y) : x(new_x), y(new_y) {}

The part after the colon is the member initialiser list: it constructs the members directly rather than default-constructing and then assigning. For ints the difference is invisible; for members that are references, const, or expensive to build, it is the only correct way.

Copy constructors — and a program that does not compile

19copy_constructors.cpp defines a copy constructor that announces itself:

Point(const Point &p) {
    std::cout << "Running our copy constructor!\n";
    x = p.x;
    y = p.y;
}
Point(const Point &p) = delete;

As checked in, the file declares the copy constructor twice — once with a body and once deleted — and g++ stops with 'Point::Point(const Point&)' cannot be overloaded. The two lines are meant as alternatives: keep the first and Point p2 = p1; prints Running our copy constructor!; keep only the second and copying a Point becomes a compile error. Deleting the copy constructor is exactly how std::unique_ptr (lesson 6) forbids copies.

Destructors and RAII

struct IntArray {
    int *array;
    IntArray(int size) { array = new int[size]; }
    ~IntArray() { std::cout << "Running our destructor\n"; delete[] array; }
};

The destructor runs automatically when the object goes out of scope. Tying a resource’s lifetime to an object’s lifetime is called RAII (resource acquisition is initialisation) and it is the central idiom of C++: files, locks and memory are all released this way.

19destructors.cpp then shows the better version, IntArray2, which holds a std::unique_ptr<int[]> and needs no destructor at all. That is also safer: copying an IntArray would copy the raw pointer, and both copies’ destructors would delete[] the same block. IntArray2 cannot be copied by accident.

Operators

20operator_overloading.cpp gives Point a + and a +=:

Point operator+(const Point &rhs) { return Point(x + rhs.x, y + rhs.y); }
Point& operator+=(const Point &rhs) { x += rhs.x; y += rhs.y; return *this; }

p1 + p2 with (10, 20) and (30, 40) gives (40, 60). += returns *this by reference so that a += b += c chains like it does for ints.

28default_comparision.cpp asks the compiler to write comparisons:

bool operator==(const S &s) const = default;
auto operator<=>(const S &s) const = default;   // C++20 "spaceship"

The defaulted versions compare members in declaration order, so {1, 2} == {1, 2} is true and {1, 2} > {1, 2} is false — the program prints 1 then 0.

Try it yourself. Fix 19copy_constructors.cpp by commenting out the = delete line, and check you get the message once for Point p2 = p1;. Then add Point p3(1, 1); p3 = p1; — does the copy constructor run? (It does not: that is copy assignment, a different function.)

View source on GitHub →