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* 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:
TruckandBicycleinherit fromVehicle, so aVehicle*can legally point to any of themgetName()(called insideshow()) isvirtual, so it's resolved at runtime- 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:
Dynamic dispatch — Wikipedia — selecting which implementation runs at runtime.
Virtual function — Wikipedia — overridable methods and how they bind.