LOGBOOK

HELP

Quiz Entry - updated: 2026.07.06

How does polymorphism work with pointers in C++?

A base-class pointer can hold any derived object, and calling a virtual method runs the correct override for the real object it points to.

One Vehicle pointer pointing in turn to a Vehicle, a Truck, and a Bicycle, each printing its own line

* One Vehicle* variable drives three different behaviours — the virtual call picks the override for whatever object it currently points to. *

int main() {
    Vehicle *v;

    v = new Vehicle(4);
    v->show();      // "Vehicle has 4 wheels."
    delete v;

    v = new Truck();
    v->show();      // "Truck has 6 wheels."
    delete v;

    v = new Bicycle();
    v->show();      // "Bicycle has 2 wheels."
    delete v;
}

This works because:

  1. Truck and Bicycle inherit from Vehicle, so a Vehicle* can legally point to any of them
  2. getName() (called inside show()) is virtual, so it's resolved at runtime
  3. The same pointer variable can therefore drive different behaviour depending on the actual object

Tip: This is the core of object-oriented design: write code against the base type once, and it automatically does the right thing for every subclass.

Go deeper:

From Quiz: REVE1 / C++ Programming | Updated: Jul 06, 2026