SyntaxPilot
Courses/C++ Coding Questions/Lesson 25
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ Coding Questions · Lesson 25 of 30

OOP output questions

virtual vs non-virtual callsthe missing virtual destructorobject slicingconstructor and destructor order

These are the notes for C++ Coding Questions, episode 25, placement practice for people who finished the SyntaxPilot C++ course. In a placement test, OOP questions usually look like this: a base class, a derived class, a main, and the question "what does this print?". Three classics: a function called through a base reference that runs the wrong version (virtual vs non-virtual), an object that loses half of itself when it is copied (object slicing), and the order in which constructors and destructors run, including the destructor that never runs (the missing virtual destructor).

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the cost.

Every program was compiled with g++ -Wall -O2 -std=c++17 main.cpp -o main (g++ 13.3, Linux x86-64), the SyntaxPilot compiler's C++ command with warnings on, and every output below is real, including the compiler errors and warnings.

Real-life pictures

In real life In C++
Sealed envelopes, all labelled "Letter" objects used through a base-class reference
A peon who reads only the label a non-virtual call: the declared type decides
A peon who opens the envelope at delivery a virtual call: the real object decides at run time
A full thali: roti, dal, sabzi, rice a whole Sms object (base part + its own data)
A one-compartment tiffin box made for a roti a vector<Notification>: room for a base object only
Only the roti fits, the rest is left out object slicing
Packing a note that says where the thali is storing a pointer (unique_ptr<Notification>)
A car factory: frame, then engine, then body construction: base, then members, then the class's own body
A scrap yard: body, then engine, then frame destruction: the exact reverse
A scrap dealer whose paper says only "Vehicle" delete through a base pointer with a non-virtual destructor

Q1: Virtual vs non-virtual calls

Problem. Notification has send(). Sms and Email derive from it and have their own send(). A function notify(const Notification& n) calls n.send(). What does it print for an Sms and an Email?

Think out loud. A derived class is a class built on another: class Sms : public Notification. Every Sms is a Notification, so it can be passed where a Notification& is expected. A reference (Notification&) is another name for an existing object; no copy is made. The question is: when we call n.send() and n really is an Sms, which send() runs?

The obvious attempt

#include <iostream>
using namespace std;

class Notification {
public:
    void send() const { cout << "generic notification\n"; }
};

class Sms : public Notification {
public:
    void send() const { cout << "SMS: your OTP is 4821\n"; }
};

class Email : public Notification {
public:
    void send() const { cout << "Email: your bill is ready\n"; }
};

void notify(const Notification& n) { n.send(); }

int main() {
    Sms s;
    Email e;
    s.send();                            // called on the object itself
    notify(s);                           // called through a Notification&
    notify(e);
    return 0;
}

Output:

SMS: your OTP is 4821
generic notification
generic notification

The direct call is right, but both calls through notify print the base version.

Why

For an ordinary member function, the compiler chooses which function to call while compiling, from the declared type of the expression. Inside notify, n is declared as const Notification&, so n.send() always means Notification::send(). This is static binding (also called early binding). It does not matter what object is really behind the reference.

The fix: virtual (and override)

Mark the function virtual in the base class. Now the choice is made at run time, from the real object: dynamic binding. In the derived classes, write override: it asks the compiler to check that this function really replaces a virtual function of the base.

#include <iostream>
using namespace std;

class Notification {
public:
    virtual void send() const { cout << "generic notification\n"; }
    void tag() const { cout << "[base tag]\n"; }    // NOT virtual
};

class Sms : public Notification {
public:
    void send() const override { cout << "SMS: your OTP is 4821\n"; }
    void tag() const { cout << "[sms tag]\n"; }
};

class Email : public Notification {
public:
    void send() const override { cout << "Email: your bill is ready\n"; }
};

void notify(const Notification& n) { n.send(); n.tag(); }

int main() {
    Sms s;
    Email e;
    notify(s);
    notify(e);
    return 0;
}

Output:

SMS: your OTP is 4821
[base tag]
Email: your bill is ready
[base tag]

send() is virtual, so the real object decides. tag() is not virtual, so the declared type decides, even though Sms has its own tag(): a derived function with the same name only replaces a base function in virtual calls if the base function is virtual. (A non-virtual function with the same name in the derived class hides the base one only when you call it on a Sms directly.)

The override trap

Someone forgets const in Email::send. With override, the compiler stops them:

#include <iostream>
using namespace std;

class Notification {
public:
    virtual void send() const { cout << "generic notification\n"; }
};

class Email : public Notification {
public:
    void send() override { cout << "Email: your bill is ready\n"; }   // const forgotten
};

int main() {
    Email e;
    const Notification& n = e;
    n.send();
    return 0;
}

Compiler output:

main.cpp:11:10: error: 'void Email::send()' marked 'override', but does not override
   11 |     void send() override { cout << "Email: your bill is ready\n"; }   // const forgotten
      |          ^~~~
main.cpp:6:18: warning: 'virtual void Notification::send() const' was hidden [-Woverloaded-virtual=]
    6 |     virtual void send() const { cout << "generic notification\n"; }
      |                  ^~~~
main.cpp:11:10: note:   by 'void Email::send()'
   11 |     void send() override { cout << "Email: your bill is ready\n"; }   // const forgotten
      |          ^~~~

send() and send() const are different functions (a different signature). Without the word override, the same program compiles with only the was hidden warning, and prints generic notification: a silent bug. Always write override.

How virtual works underneath

Every object of a class with virtual functions carries a hidden pointer, the vptr, to its class's table of virtual functions, the vtable. A virtual call reads the vptr, looks up the slot for send, and jumps there. That is one extra memory read: O(1), but it stops the compiler from inlining the call. The vptr is why sizeof(Notification) is 8 bytes (on 64-bit) even though it has no data members (Q2 prints it).

Cost. A virtual call: O(1) time; each object pays one pointer (8 bytes) of space, each class one vtable.

Q2: Object slicing

Problem. Keep notifications in one vector, an outbox, and send them all later. send() is virtual now. The Sms also stores who it goes to.

Think out loud. If virtual calls work, putting an Sms into a vector<Notification> and calling send() should print the SMS message. Edge cases: a derived class with extra data, and passing a derived object to a function by value.

The obvious attempt

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Notification {
public:
    virtual void send() const { cout << "generic notification\n"; }
};

class Sms : public Notification {
public:
    string to = "Asha";
    void send() const override { cout << "SMS to " << to << ": OTP 4821\n"; }
};

int main() {
    Sms s;
    vector<Notification> outbox;         // a box of Notifications
    outbox.push_back(s);                 // put the SMS in
    s.send();
    outbox[0].send();
    cout << sizeof(Sms) << " bytes vs " << sizeof(Notification) << " bytes\n";
    return 0;
}

Output:

SMS to Asha: OTP 4821
generic notification
40 bytes vs 8 bytes

Why

A vector<Notification> stores Notification objects, each exactly 8 bytes. push_back(s) copies s into that space using Notification's copy constructor, which copies only the Notification part. The to string and the "I am an Sms" information are cut off. This is object slicing. The copy is not a broken Sms: it really is a plain Notification (its vptr points to Notification's vtable), so the virtual call correctly runs Notification::send().

sizeof(Sms) is 40: 8 for the vptr plus 32 for the std::string. sizeof(Notification) is 8: just the vptr.

Slicing happens whenever a derived object is copied into a base object: Notification n = s;, vector<Notification>, and a function parameter void f(Notification n) taken by value.

The fix: store pointers

Pointers and references do not copy the object, so nothing is cut off. unique_ptr<Notification> owns the object and deletes it automatically; make_unique<Sms>() creates one. Because the vector will delete Sms and Email objects through a Notification pointer, the base class needs a virtual destructor (Q3 explains why).

#include <iostream>
#include <vector>
#include <string>
#include <memory>
using namespace std;

class Notification {
public:
    virtual void send() const { cout << "generic notification\n"; }
    virtual ~Notification() = default;
};

class Sms : public Notification {
public:
    string to = "Asha";
    void send() const override { cout << "SMS to " << to << ": OTP 4821\n"; }
};

class Email : public Notification {
public:
    void send() const override { cout << "Email: your bill is ready\n"; }
};

int main() {
    vector<unique_ptr<Notification>> outbox;   // a box of POINTERS
    outbox.push_back(make_unique<Sms>());
    outbox.push_back(make_unique<Email>());
    for (const auto& n : outbox) n->send();
    return 0;
}

Output:

SMS to Asha: OTP 4821
Email: your bill is ready

Cost. Sending n notifications: O(n) time; the vector holds n pointers (8 bytes each) plus the objects on the heap.

Q3: Constructor and destructor order, and the virtual destructor

Problem. struct Car : Vehicle { Engine engine; }. Every constructor and destructor prints a line. (1) Make a Car inside braces: in what order are the parts built and removed? (2) Make a Car with new through a Vehicle* and delete it: is the whole car removed?

Think out loud. A constructor runs when an object is created; a destructor (the function named ~ClassName) runs automatically when it dies: at the closing brace for a local object, or at delete for a heap object.

Part 1: build and scrap order

#include <iostream>
using namespace std;

struct Engine {
    Engine()  { cout << "Engine built\n"; }
    ~Engine() { cout << "Engine removed\n"; }
};

struct Vehicle {
    Vehicle()  { cout << "Vehicle frame built\n"; }
    ~Vehicle() { cout << "Vehicle frame removed\n"; }
    virtual void drive() { cout << "driving\n"; }
};

struct Car : Vehicle {
    Engine engine;                       // a member
    Car()  { cout << "Car body built\n"; }
    ~Car() { cout << "Car body removed\n"; }
    void drive() override { cout << "Car: vroom\n"; }
};

int main() {
    {
        Car c;
        cout << "--- using the car ---\n";
    }                                    // c dies here
    return 0;
}

Output:

Vehicle frame built
Engine built
Car body built
--- using the car ---
Car body removed
Engine removed
Vehicle frame removed

The rule. Construction: base classes first, then members in the order they are declared in the class (not the order in the initializer list), then the constructor's own body. Destruction: the exact reverse. A member can rely on the base being ready; the body can rely on all members being ready; and nothing is destroyed while something built after it still exists.

Part 2: delete through a base pointer

Same classes, a new main:

int main() {
    Vehicle* p = new Car;
    p->drive();
    cout << "--- scrap it through a Vehicle* ---\n";
    delete p;
    return 0;
}

Compiler output and program output:

main.cpp: In function 'int main()':
main.cpp:26:5: warning: deleting object of polymorphic class type 'Vehicle' which has non-virtual destructor might cause undefined behavior [-Wdelete-non-virtual-dtor]
   26 |     delete p;
      |     ^~~~~~~~
Vehicle frame built
Engine built
Car body built
Car: vroom
--- scrap it through a Vehicle* ---
Vehicle frame removed

drive() is virtual, so Car: vroom is right. But delete p removed only the frame.

Why

~Vehicle() is not virtual, so delete p chooses the destructor from the declared type of p, exactly like send() in Q1. Deleting a derived object through a base pointer whose destructor is not virtual is undefined behaviour: the C++ standard promises nothing. With g++ here, ~Car() and ~Engine() were simply skipped. If Car owned a string, a vector or a file, that memory or file would leak (never be given back).

Note: g++ only gives -Wdelete-non-virtual-dtor when the class is polymorphic (has at least one virtual function). Without any virtual function there is no warning at all, and the bug is just as real.

The fix

struct Vehicle {
    Vehicle()  { cout << "Vehicle frame built\n"; }
    virtual ~Vehicle() { cout << "Vehicle frame removed\n"; }
    virtual void drive() { cout << "driving\n"; }
};

Output of part 2 with the virtual destructor (no warning):

Vehicle frame built
Engine built
Car body built
Car: vroom
--- scrap it through a Vehicle* ---
Car body removed
Engine removed
Vehicle frame removed

The rule. A class meant to be used through a base pointer (it has virtual functions, or derived objects are deleted through it) gets a virtual destructor: virtual ~Base() = default; is enough. If a base class is never meant to be deleted through a pointer, make its destructor protected instead.

Cost. Building or destroying an object is O(number of parts). A virtual destructor costs nothing extra when the class already has a vptr.

Cost summary

Program Result Cost
notify() with a non-virtual send() generic notification twice O(1), static binding
notify() with virtual send() the right message O(1), one vtable lookup
override on the wrong signature compile error caught at compile time
vector<Notification> of an Sms sliced: generic notification O(n) copies
vector<unique_ptr<Notification>> the right messages O(n), n pointers
delete via Vehicle*, non-virtual ~Vehicle warning, only the frame removed (UB)
delete via Vehicle*, virtual ~Vehicle body, engine, frame removed O(parts)

Common mistakes (and the real results)

Mistake What you see Why Fix
send() not virtual, called through a base & or * no error: the base version runs static binding: the declared type decides virtual in the base class
void send() override when the base has send() const error: 'void Email::send()' marked 'override', but does not override a different signature match the signature exactly
the same mistake without override warning: ... was hidden [-Woverloaded-virtual=], base version runs it is a new, unrelated function always write override
vector<Base> of derived objects no error: the base version runs, derived data lost object slicing vector<unique_ptr<Base>>
void f(Shape s) taking a base class by value no error: by value: shape slicing at the call const Shape&
delete through a Base*, ~Base() not virtual warning: deleting object of polymorphic class type 'Vehicle' which has non-virtual destructor might cause undefined behavior the derived destructor is skipped virtual ~Base()
calling a virtual function in a constructor the base version runs the derived part does not exist yet don't rely on it; call it after construction
expecting the derived constructor first no error: base is built first base → members → body destruction is the reverse
creating an object of an abstract class error: cannot declare variable 'n' to be of abstract type 'Notification' it has a pure virtual function create a derived class

Mini project: a notification dispatcher

A food-delivery app sends "your order is out for delivery" over different channels. The base class is abstract: it has pure virtual functions (= 0), so it cannot be created by itself and every channel must implement them. send() itself is not virtual: the steps are the same for every channel, and it calls the virtual channel() and cost() inside (this pattern is called the template method). A small factory function turns a word like sms into the right object. Push is marked final, so nobody can derive from it.

#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;

class Notification {                       // abstract: cannot be created by itself
public:
    explicit Notification(string to) : to(move(to)) {}
    virtual ~Notification() = default;     // deleted through a base pointer: virtual
    virtual string channel() const = 0;    // pure virtual: every channel must say its name
    virtual double cost() const = 0;       // rupees per message
    void send(const string& text) const {  // NOT virtual: the same steps for all
        cout << "[" << channel() << "] to " << to << ": " << text
             << " (Rs " << cost() << ")\n";
    }
protected:
    string to;
};

class Sms : public Notification {
public:
    using Notification::Notification;      // reuse the base constructor
    string channel() const override { return "SMS"; }
    double cost() const override { return 0.25; }
};

class Email : public Notification {
public:
    using Notification::Notification;
    string channel() const override { return "Email"; }
    double cost() const override { return 0.0; }
};

class Push final : public Notification {   // final: nobody can derive from Push
public:
    using Notification::Notification;
    string channel() const override { return "Push"; }
    double cost() const override { return 0.05; }
};

unique_ptr<Notification> make(const string& kind, const string& to) {
    if (kind == "sms") return make_unique<Sms>(to);
    if (kind == "email") return make_unique<Email>(to);
    if (kind == "push") return make_unique<Push>(to);
    return nullptr;                        // unknown kind
}

int main() {
    vector<unique_ptr<Notification>> outbox;
    string kind, to;
    while (cin >> kind >> to) {
        auto n = make(kind, to);
        if (n) outbox.push_back(move(n));
        else cout << "unknown channel: " << kind << "\n";
    }
    double total = 0;
    for (const auto& n : outbox) {
        n->send("your order is out for delivery");
        total += n->cost();
    }
    cout << outbox.size() << " sent, total cost Rs " << total << "\n";
    return 0;
}

Input:

sms Asha
email Ravi
fax Neha
push Priya

Output:

unknown channel: fax
[SMS] to Asha: your order is out for delivery (Rs 0.25)
[Email] to Ravi: your order is out for delivery (Rs 0)
[Push] to Priya: your order is out for delivery (Rs 0.05)
3 sent, total cost Rs 0.3

Try: add a WhatsApp channel. You only write one new class and one line in make(); main and send() do not change. That is the point of virtual functions.

Practice questions (with solutions)

1. Your turn: predict the output.

struct Pen   { Pen()  { cout << "P"; }  ~Pen()  { cout << "p"; } };
struct Base  { Base() { cout << "B"; }  virtual ~Base() { cout << "b"; } };
struct Kid : Base { Pen pen;  Kid() { cout << "K"; }  ~Kid() { cout << "k"; } };

int main() { Base* x = new Kid;  delete x;  Kid y; }

Then remove the word virtual and predict again.

Solution

With virtual ~Base():

BPKkpbBPKkpb

new Kid builds base B, member P, body K. delete x (virtual destructor) removes body k, member p, base b. Then Kid y prints BPK, and at the closing brace of main kpb.

Without virtual:

BPKbBPKkpb

delete x runs only ~Base(): b. ~Kid() and ~Pen() are skipped (undefined behaviour). y is a real Kid, so it is still destroyed correctly. Note: here g++ gives no warning, because Base has no virtual function at all, so it is not "polymorphic". The bug is silent.

2. A vector<unique_ptr<Shape>> with area(). Make an abstract Shape with area() and name(), a Rect and a Circle, store them in one vector and print each area and the total.

Solution
#include <iostream>
#include <memory>
#include <vector>
using namespace std;

struct Shape {
    virtual double area() const = 0;
    virtual const char* name() const = 0;
    virtual ~Shape() = default;
};
struct Rect : Shape {
    double w, h;
    Rect(double w, double h) : w(w), h(h) {}
    double area() const override { return w * h; }
    const char* name() const override { return "rect"; }
};
struct Circle : Shape {
    double r;
    explicit Circle(double r) : r(r) {}
    double area() const override { return 3.14159 * r * r; }
    const char* name() const override { return "circle"; }
};

int main() {
    vector<unique_ptr<Shape>> shapes;
    shapes.push_back(make_unique<Rect>(4, 5));
    shapes.push_back(make_unique<Circle>(1));
    double total = 0;
    for (const auto& s : shapes) {
        cout << s->name() << " " << s->area() << "\n";
        total += s->area();
    }
    cout << "total " << total << "\n";
    return 0;
}

Output:

rect 20
circle 3.14159
total 23.1416

3. Find the slicing.

#include <iostream>
using namespace std;

struct Shape {
    virtual const char* name() const { return "shape"; }
    virtual ~Shape() = default;
};
struct Circle : Shape {
    const char* name() const override { return "circle"; }
};

void printByValue(Shape s)      { cout << "by value: " << s.name() << "\n"; }
void printByRef(const Shape& s) { cout << "by ref:   " << s.name() << "\n"; }

int main() {
    Circle c;
    printByValue(c);
    printByRef(c);
    return 0;
}
Solution

Output:

by value: shape
by ref:   circle

printByValue makes a new Shape from c: slicing. printByRef refers to the real Circle. Rule: take polymorphic objects by const& (or a pointer), never by value.

4. final. Mark a class final and try to derive from it.

Solution
struct Push final { };
struct Loud : Push { };
int main() { return 0; }

Compiler output:

main.cpp:2:8: error: cannot derive from 'final' base 'Push' in derived type 'Loud'
    2 | struct Loud : Push { };
      |        ^~~~

final on a class forbids deriving from it; final on a virtual function (void send() const final) forbids overriding it further.

Quick quiz

1. What does this print? (the episode quiz)

struct A { virtual void f() { cout << "A"; } };
struct B : A { void f() override { cout << "B"; } };

void byValue(A a) { a.f(); }
void byRef(A& a)  { a.f(); }

B b;  byValue(b);  byRef(b);

(A) BB (B) AB (C) AA (D) BA

Answer

(B) AB. byValue copies b into a new A (slicing), so A::f runs. byRef refers to the real B, so the virtual call runs B::f. Real output: AB.

2. What does this print?

struct Base { void show() { cout << "Base\n"; } };
struct Derived : Base { void show() { cout << "Derived\n"; } };
int main() { Derived d; Base* p = &d; p->show(); d.show(); }
Answer
Base
Derived

show() is not virtual: through Base* the declared type decides.

3. What does this print?

struct A { A() { cout << "A"; } ~A() { cout << "a"; } };
struct B { B() { cout << "B"; } ~B() { cout << "b"; } };
struct C : A { B b1; B b2; C() { cout << "C"; } ~C() { cout << "c"; } };
int main() { C x; cout << "|"; }
Answer
ABBC|cbba

Base A, then members b1, b2 in declaration order, then the body C. At the end of main, the reverse.

4. A virtual call inside a constructor.

struct Base {
    Base() { hello(); }
    virtual void hello() { cout << "Base hello\n"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    void hello() override { cout << "Derived hello\n"; }
};
int main() { Derived d; d.hello(); }
Answer
Base hello
Derived hello

While Base() runs, the Derived part does not exist yet, so the object is still a Base and the virtual call goes to Base::hello. The same is true inside a destructor.

5. sizeof of a class with no data members but one virtual function, on a 64-bit system?

Answer

8 bytes: the hidden vptr (the episode printed sizeof(Notification) = 8).

Interview questions

  1. What is a virtual function? A member function whose call through a base reference or pointer is decided at run time by the real object's type (dynamic binding).
  2. Static vs dynamic binding? Static: the compiler chooses from the declared type. Dynamic: chosen at run time from the real object, through the vtable.
  3. What is a vtable and a vptr? A per-class table of pointers to its virtual functions, and a hidden pointer in every object to its class's table.
  4. Why write override? The compiler checks that the function really overrides a base virtual function; a wrong signature becomes a compile error instead of a silent new function.
  5. What is object slicing? Copying a derived object into a base object keeps only the base part; the derived data and behaviour are lost.
  6. How do you avoid slicing? Pass and store polymorphic objects by reference or pointer (const Base&, unique_ptr<Base>), never by value.
  7. In what order are constructors called? Base classes, then members in declaration order, then the constructor body. Destructors run in the reverse order.
  8. Why does a base class need a virtual destructor? So that delete through a base pointer runs the derived destructor; otherwise it is undefined behaviour and derived resources leak.
  9. Can a constructor be virtual? No. When a constructor runs, the object's type is being decided; there is no vptr to use yet. (A "virtual constructor" is a pattern: a virtual clone() or a factory.)
  10. What happens when you call a virtual function from a constructor? The version of the class being constructed runs, not the derived one.
  11. What is an abstract class? A class with at least one pure virtual function (= 0); you cannot create objects of it, only of derived classes that implement them.
  12. What does final do? On a class: it cannot be derived from. On a virtual function: it cannot be overridden further.
  13. Function hiding vs overriding? A derived function with the same name hides all base functions of that name; it overrides only if the base one is virtual with the same signature.

Glossary

Term Meaning Example
Base class The class another class is built on Notification
Derived class A class built on another, inheriting its members class Sms : public Notification
Inheritance Building a class on another (an "is-a" relation) every Sms is a Notification
Reference Another name for an existing object; no copy const Notification& n
Static binding The function is chosen at compile time from the declared type non-virtual tag()
Dynamic binding The function is chosen at run time from the real object virtual send()
Virtual function A function that uses dynamic binding virtual void send() const
override Asks the compiler to check that a function overrides a virtual one void send() const override
Signature A function's name, parameter types and qualifiers like const send() const
Function hiding A derived name hides the base function of the same name Sms::tag()
Polymorphism One interface, many behaviours, chosen at run time notify(sms), notify(email)
Polymorphic class A class with at least one virtual function Vehicle
vtable A per-class table of virtual function addresses used by n.send()
vptr The hidden pointer in each object to its vtable why sizeof(Notification) = 8
Object slicing Copying a derived object into a base object, losing the derived part vector<Notification>
unique_ptr A smart pointer that owns one object and deletes it unique_ptr<Notification>
make_unique Creates an object and its unique_ptr make_unique<Sms>()
Constructor Runs when an object is created Car()
Destructor Runs automatically when an object dies ~Car()
Member A variable inside a class Engine engine;
Virtual destructor A destructor that delete through a base pointer finds virtual ~Vehicle()
Undefined behaviour Code the language gives no meaning to: anything may happen deleting via a base pointer, non-virtual destructor
Memory leak Memory taken and never given back skipped ~Car()
Abstract class A class with a pure virtual function; cannot be created Notification in the mini project
Pure virtual function A virtual function with no body, = 0 virtual string channel() const = 0;
final Forbids deriving from a class or overriding a function class Push final
Factory function A function that creates the right derived object make("sms", "Asha")
Template method A non-virtual function whose steps call virtual functions send() calls channel()

Summary

  • A normal member call follows the declared type (static binding). virtual lets the real object decide at run time (dynamic binding), through the vtable.
  • Always write override in derived classes: a wrong signature becomes a compile error, not a silent bug.
  • Copying a derived object into a base object slices it; store and pass polymorphic objects by reference or pointer (vector<unique_ptr<Base>>).
  • Objects are built base → members → body and destroyed in the reverse order.
  • If objects are deleted through a base pointer, the base needs a virtual destructor; without it, it is undefined behaviour and derived parts are skipped.

Next episode: pointers and memory questions: returning a reference to a local (dangling), new[] with the wrong delete, and memory leaks versus unique_ptr and shared_ptr.