Notes
All notes

Object-Oriented Programming (C++ Core #4)

Classes in C++ are about three things: how objects are created and destroyed, what happens when they are copied or moved, and which function actually runs when you call through a base pointer. Predict-the-output questions live in all three.

Classes, objects, and this

Classes and objects are the two nouns: a class is the definition, an object is an instance of it. A class defines members and access. Every non-static member function has an implicit this pointer to the object it was called on.

class Point {
    int x = 0, y = 0;          // private by default
public:
    Point() = default;
    Point(int x, int y) : x(x), y(y) {}   // member init list

    int getX() const { return x; }         // const: this is const Point*
    void setX(int v) { this->x = v; }
};

Members are initialized in declaration order, not in the order written in the initializer list. If one member’s initializer reads another, the order decides the result:

struct S {
    int a;
    int b;
    S() : b(1), a(b) {}    // a is initialized first, using uninitialized b
};

That is a bug the compiler warns about (-Wreorder) and a favourite exam question.

struct and class differ only in default access and default inheritance: public for struct, private for class.

QQuestionWhy does S() : b(1), a(b) {} not set a to 1?
ASolution

Members initialize in declaration order, so a is initialized before b. The initializer list order is ignored; only the declaration order matters.

Constructors and destructors

A constructor builds the object; a destructor tears it down. The compiler generates a default constructor only if you declare no other constructor, and generates a destructor always.

struct S {
    S()          { std::cout << "ctor\n"; }
    ~S()         { std::cout << "dtor\n"; }
};

void f() {
    S a;                  // ctor
    { S b; }              // ctor, dtor
}                         // a's dtor

Destructors run in reverse order of construction, which matters for members: members are destroyed after the destructor body runs, in reverse declaration order.

A constructor can throw. If it does, the object is not constructed, its destructor does not run, but destructors for already-constructed members and base classes do run (Ch. 9).

QQuestionHow many times does ~S run for S a; S b; in one scope?
ASolution

Twice, in reverse order: b then a.

Copy constructor and copy assignment

The copy constructor creates a new object from an existing one. The copy assignment operator replaces the contents of an existing object.

struct S {
    S()                        { std::cout << "default\n"; }
    S(const S&)                { std::cout << "copy ctor\n"; }
    S& operator=(const S&)     { std::cout << "copy assign\n"; return *this; }
    ~S()                       { std::cout << "dtor\n"; }
};

S a;            // default
S b = a;        // copy ctor (initialization, not assignment)
S c(a);         // copy ctor
b = a;          // copy assign (b already exists)

S b = a; looks like assignment but is initialization, so it calls the copy constructor. That distinction is the single most common copy-versus-assignment question.

The compiler-generated copy does a memberwise copy. For a class holding a raw pointer, that copies the pointer, not the data:

class Buffer {
    int* data;
    size_t n;
public:
    Buffer(size_t n) : data(new int[n]), n(n) {}
    ~Buffer() { delete[] data; }
    // no copy ctor: compiler copies data and n
};

Buffer a(10);
Buffer b = a;      // b.data == a.data
                   // both destructors delete the same pointer: double free

A correct deep copy allocates its own storage:

Buffer(const Buffer& o) : data(new int[o.n]), n(o.n) {
    std::copy(o.data, o.data + o.n, data);
}

Buffer& operator=(const Buffer& o) {
    if (this == &o) return *this;         // self-assignment check
    int* fresh = new int[o.n];            // allocate first: exception safety
    std::copy(o.data, o.data + o.n, fresh);
    delete[] data;                        // then release the old buffer
    data = fresh;
    n = o.n;
    return *this;
}

The assignment operator returns *this by reference so that a = b = c works, and it checks self-assignment because deleting your own buffer before copying from it destroys the source.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum width=1.5cm, minimum height=0.55cm, font=\scriptsize},
  a/.style={->, thick}]
  \node[b, fill=blue!12] (a1) at (0,1.2) {a.data};
  \node[b, fill=orange!15] (buf) at (3.2,1.2) {heap buffer};
  \node[b, fill=blue!12] (b1) at (0,0) {b.data};
  \draw[a] (a1) -- (buf);
  \draw[a, red!65, dashed] (b1) -- (buf);
  \node[font=\scriptsize, anchor=west] at (4.4,0.6) {shallow copy: two owners, one buffer};
\end{tikzpicture}
QQuestionS b = a; where a is an existing S — which special member runs?
ASolution

The copy constructor, because b is being created. b = a; on a later line calls copy assignment.

Move constructor and move assignment

Move operations steal resources instead of copying them. They take an rvalue reference T&&, which binds to temporaries and to objects you explicitly mark with std::move.

Buffer(Buffer&& o) noexcept : data(o.data), n(o.n) {
    o.data = nullptr;         // leave the source destructible
    o.n = 0;
}

Buffer& operator=(Buffer&& o) noexcept {
    if (this != &o) {
        delete[] data;
        data = o.data;
        n = o.n;
        o.data = nullptr;
        o.n = 0;
    }
    return *this;
}

A moved-from object must be left in a valid state: you may destroy it or assign to it, but you may not assume its contents. For standard containers that state is usually “empty”, but the standard only promises “valid but unspecified”.

std::move itself does not move anything. It is a cast to an rvalue reference, so that overload resolution picks the move overload:

std::string a = "hello";
std::string b = std::move(a);   // move ctor
// a is valid but empty in practice; do not rely on its value

Move constructors should be noexcept. std::vector reallocates by moving when the move constructor is noexcept; otherwise it copies, to keep the strong exception guarantee.

QQuestionAfter std::string b = std::move(a);, is a empty?
ASolution

It is valid but unspecified. In practice all major implementations leave it empty, but the standard does not require that, so code must not depend on it.

Rule of Three, Five, and Zero

class Good {                 // rule of zero
    std::vector<int> data;
    std::string name;
public:
    Good(std::vector<int> d, std::string n) : data(std::move(d)), name(std::move(n)) {}
};

Declaring a destructor, copy constructor, or copy assignment suppresses the implicit move operations, which is why a class with ~Buffer() but no move constructor silently copies. Declare the moves explicitly (or delete the copies) if the class should be movable.

QQuestionA class has a user-declared destructor and nothing else. Is it

movable?

ASolution

No. Declaring a destructor prevents the implicit move constructor and move assignment from being generated. Copies are used instead, and the move attempts fall back to the copy operations.

Inheritance

Inheritance shares interface and implementation. The derived object contains a base subobject, constructed before the derived members.

struct Base {
    Base()  { std::cout << "Base ctor\n"; }
    ~Base() { std::cout << "Base dtor\n"; }
};
struct Member {
    Member()  { std::cout << "Member ctor\n"; }
    ~Member() { std::cout << "Member dtor\n"; }
};
struct Derived : Base {
    Member m;
    Derived()  { std::cout << "Derived ctor\n"; }
    ~Derived() { std::cout << "Derived dtor\n"; }
};

Derived d;
// Base ctor
// Member ctor
// Derived ctor
// Derived dtor
// Member dtor
// Base dtor

Constructor and destructor execution order: base, then members in declaration order, then the constructor body. Destruction is the exact reverse.

Access specifiers on inheritance control conversion, not member access:

class D : public Base    { };   // D* converts to Base*, public members keep access
class E : protected Base { };   // only D and its derived classes know about Base
class F : private Base   { };   // Base is an implementation detail
QQuestionIn what order are the base class and the members destroyed?
ASolution

Reverse of construction: derived destructor body, members in reverse declaration order, then the base destructor.

Polymorphism and virtual functions

A virtual function is chosen at runtime based on the dynamic type of the object. Without virtual, the choice is made at compile time from the static type.

struct Base {
    virtual void f() { std::cout << "Base::f\n"; }
    void g()         { std::cout << "Base::g\n"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    void f() override { std::cout << "Derived::f\n"; }
    void g()         { std::cout << "Derived::g\n"; }
};

Base* p = new Derived;
p->f();      // Derived::f  (virtual dispatch)
p->g();      // Base::g     (static binding)
delete p;    // ok: virtual destructor

override asks the compiler to verify that the function really overrides a base virtual. Without it, a signature mismatch silently creates a new function:

struct D : Base {
    void f(int) override;      // error: no such base function
    void f() const override;   // error: different signature
};

final stops further overriding.

The usual implementation is a vtable: one table of function pointers per class, and one hidden pointer (vptr) per object.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum width=1.7cm, minimum height=0.55cm, font=\scriptsize, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!12] (o) at (0,0) {Derived object\\vptr};
  \node[b, fill=green!18] (v) at (3.4,0) {Derived vtable};
  \node[b, fill=green!18] (f1) at (6.3,0.7) {Derived::f};
  \node[b, fill=green!18] (f2) at (6.3,-0.7) {Derived::~Derived};
  \draw[a] (o) -- (v);
  \draw[a] (v) -- (f1);
  \draw[a] (v) -- (f2);
  \node[font=\scriptsize, anchor=north] at (0,-0.5) {one pointer per object};
  \node[font=\scriptsize, anchor=north] at (3.4,-1.2) {one table per class};
\end{tikzpicture}
QQuestionp->g() calls Base::g even though the object is a Derived. Why?
ASolution

g is not virtual, so the call is resolved statically from the type of p (Base*). Only virtual functions go through the vtable.

Abstract classes and interfaces

A pure virtual function has no definition in the base and makes the class abstract: you cannot create objects of that type, only pointers and references to it. Derived classes must override every pure virtual function, or they stay abstract too.

struct Shape {
    virtual double area() const = 0;     // pure virtual
    virtual ~Shape() = default;
};

struct Circle : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
};

// Shape s;                    // error: abstract class
Shape* p = new Circle(2.0);     // ok: polymorphic use
std::cout << p->area();         // 12.56636
delete p;

A pure virtual function may still have a body (defined out of line), which derived classes can call explicitly with Shape::area(). That is rare but legal; the declaration = 0 is what makes the class abstract, not the absence of a body.

A class with only pure virtual functions and a virtual destructor is the C++ version of an interface. It has no data, so it costs one vptr per object.

QQuestionCan you create an object of a class that has one pure virtual

function and one ordinary virtual function?

ASolution

No. Any pure virtual function makes the whole class abstract. You can only create derived classes that override it.

Virtual destructors

Deleting a derived object through a base pointer requires a virtual destructor.

struct Base {
    ~Base() {}                 // not virtual
};
struct Derived : Base {
    int* data = new int[100];
    ~Derived() { delete[] data; }
};

Base* p = new Derived;
delete p;                      // UB: only ~Base runs, data leaks

The rule: a class with virtual functions should have a virtual destructor, because it is meant to be used polymorphically. std::unique_ptr<Base> deleting a Derived has the same requirement.

= default on the destructor in a polymorphic base is the usual fix:

struct Base {
    virtual ~Base() = default;
};
QQuestionWhy is a non-virtual destructor UB rather than just a leak?
ASolution

The standard says deleting through a base pointer with a non-virtual destructor is undefined behaviour, because the deallocation function may use the wrong size or the wrong type. A leak is only the harmless-looking outcome.

Object slicing

Copying a derived object into a base object slices off the derived part. The result is a genuine Base object, so virtual calls dispatch to Base.

struct Base { virtual void f() const { std::cout << "Base\n"; } };
struct Derived : Base { void f() const override { std::cout << "Derived\n"; } };

void take(Base b) { b.f(); }

Derived d;
take(d);              // Base: sliced copy

void takeRef(const Base& b) { b.f(); }
takeRef(d);           // Derived: no copy, dynamic type preserved

Slicing also happens in containers: std::vector<Base> cannot hold Derived objects without losing the derived part. Use std::vector<std::unique_ptr<Base>> or references/wrappers.

QQuestionWhy does passing by value lose polymorphism?
ASolution

The copy constructor of Base is used to create the parameter, so the object really is a Base. Virtual dispatch uses the dynamic type, which is now Base.

Virtual dispatch during construction and destruction

Inside a base constructor or destructor, the dynamic type is the base being constructed or destroyed. Virtual calls therefore go to the base version, not the derived override.

struct Base {
    Base()  { f(); }
    virtual void f() { std::cout << "Base::f\n"; }
    virtual ~Base() { f(); }
};
struct Derived : Base {
    void f() override { std::cout << "Derived::f\n"; }
};

Derived d;      // prints Base::f once from the ctor, Base::f again from ~Base

A pure virtual call in a constructor or destructor is worse: it is UB, and on typical implementations it terminates the program.

struct B {
    B() { f(); }                 // pure virtual call: terminates
    virtual void f() = 0;
};

The reason is the same in both cases: the vptr is set to the base’s vtable while the base part is being built or torn down, and the derived part does not exist yet (or no longer exists).

QQuestionA base constructor calls a virtual function that the derived class

overrides. Which one runs, and why?

ASolution

The base version. During base construction the object’s dynamic type is the base class, because the derived members have not been constructed.

Deep: copy versus assignment, and dispatch

Copy versus assignment. Four situations, four different results:

S a;              // default ctor
S b = a;          // copy ctor (initialization)
S c(a);           // copy ctor
b = a;            // copy assignment
S d = std::move(a);  // move ctor (or copy if no move ctor)
b = std::move(c);    // move assignment (or copy assignment)

Two rules that decide exam answers:

  1. Initialization of a new object uses a constructor, never assignment.
  2. Assignment uses operator= and requires an already-constructed object.

Return values are the third case. Since C++17, returning a prvalue constructs the result directly in the caller’s storage (guaranteed copy elision), so no copy or move constructor runs for return S{};. Returning a named local (return x;) is not guaranteed elided, but the compiler is allowed to elide it, and since C++17 the move is implicit if elision does not happen.

Dispatch. Three rules:

struct B { virtual void f() { std::cout << "B\n"; } };
struct D : B { void f() override { std::cout << "D\n"; } };

D d;
B& r = d;
r.f();        // D
r.B::f();     // B, explicit qualification
QQuestionS b = a; then later b = a; — how many copy constructor calls and

how many assignment calls?

ASolution

One copy constructor (for b’s initialization) and one copy assignment (the later statement). The first line is initialization, the second is assignment.

Bugs and edge cases

QQuestionA class has a std::vector member and a user-declared destructor.

What special members should you think about?

ASolution

Declaring the destructor suppresses implicit moves, so the class copies on std::move unless you add move operations or remove the destructor (rule of zero).

Next: Templates and Language Features (C++ Core #5) — deduction, lambdas, constexpr, and move semantics.