Runtime polymorphism lets a program decide which function to use while it is running, not before. This helps make programs flexible and easy to change.
Runtime polymorphism in C++
class Base { public: virtual void show() { // base class version } }; class Derived : public Base { public: void show() override { // derived class version } };
The keyword virtual before a function in the base class tells C++ to use runtime polymorphism.
The override keyword in the derived class helps catch mistakes and shows you are replacing the base function.
Animal with a virtual function sound(). The derived class Dog changes the sound.class Animal { public: virtual void sound() { std::cout << "Some sound" << std::endl; } }; class Dog : public Animal { public: void sound() override { std::cout << "Bark" << std::endl; } };
Animal* points to a Dog object. Calling sound() runs the Dog version because of runtime polymorphism.Animal* pet = new Dog();
pet->sound();This program creates two shapes: a circle and a square. Both are accessed through pointers of the base class Shape. When draw() is called, the program decides at runtime which version to use, showing runtime polymorphism.
#include <iostream> class Shape { public: virtual void draw() { std::cout << "Drawing a shape" << std::endl; } }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle" << std::endl; } }; class Square : public Shape { public: void draw() override { std::cout << "Drawing a square" << std::endl; } }; int main() { Shape* shape1 = new Circle(); Shape* shape2 = new Square(); shape1->draw(); // Calls Circle's draw shape2->draw(); // Calls Square's draw delete shape1; delete shape2; return 0; }
Always declare base class functions as virtual to enable runtime polymorphism.
Use override in derived classes to avoid mistakes and improve code clarity.
Remember to delete objects created with new to avoid memory leaks.
Runtime polymorphism lets programs choose the right function during execution.
Use virtual functions in base classes and override them in derived classes.
This helps write flexible and reusable code that works with many object types.
Practice
virtual functions in C++ runtime polymorphism?Solution
Step 1: Understand virtual functions role
Virtual functions allow a base class to declare a function that derived classes can override.Step 2: Explain runtime decision
At runtime, the program decides which overridden function to call based on the actual object type.Final Answer:
To allow derived classes to override base class methods and decide at runtime which method to call -> Option DQuick Check:
Virtual functions enable runtime method selection [OK]
- Thinking virtual speeds up function calls
- Believing virtual prevents overriding
- Confusing virtual with memory allocation
Solution
Step 1: Recall virtual function syntax
The keywordvirtualcomes before the return type in the function declaration.Step 2: Match correct syntax
virtual void display(); correctly placesvirtualbeforevoid display();Final Answer:
virtual void display(); -> Option CQuick Check:
Virtual keyword precedes return type [OK]
- Placing virtual after function name
- Using virtual as a label or modifier incorrectly
- Missing semicolon after declaration
class Base {
public:
virtual void show() { std::cout << "Base"; }
};
class Derived : public Base {
public:
void show() override { std::cout << "Derived"; }
};
int main() {
Base* ptr = new Derived();
ptr->show();
delete ptr;
return 0;
}Solution
Step 1: Identify virtual function usage
Theshow()function inBaseis virtual and overridden inDerived.Step 2: Understand pointer type and object type
The pointer is of typeBase*but points to aDerivedobject, so the overriddenshow()inDerivedis called at runtime.Final Answer:
Derived -> Option AQuick Check:
Virtual function calls derived version [OK]
- Expecting base class method output
- Confusing pointer type with object type
- Ignoring virtual keyword effect
class Animal {
public:
void sound() { std::cout << "Animal sound"; }
};
class Dog : public Animal {
public:
void sound() { std::cout << "Bark"; }
};
int main() {
Animal* a = new Dog();
a->sound();
delete a;
return 0;
}Solution
Step 1: Check base class function declaration
The base class functionsound()is not declaredvirtual, so no runtime polymorphism occurs.Step 2: Effect on function call
Becausesound()is not virtual, callinga->sound()calls the base class version, not the derived one.Final Answer:
Missing virtual keyword in base class function -> Option BQuick Check:
Virtual needed for runtime polymorphism [OK]
- Assuming override works without virtual
- Thinking pointer type causes error
- Ignoring virtual keyword importance
ptr->identify() is called?class Shape {
public:
virtual void identify() { std::cout << "Shape"; }
};
class Circle : public Shape {
public:
void identify() override { std::cout << "Circle"; }
};
class ColoredCircle : public Circle {
public:
void identify() override { std::cout << "Colored Circle"; }
};
int main() {
Shape* ptr = new ColoredCircle();
ptr->identify();
delete ptr;
return 0;
}Solution
Step 1: Trace virtual function overrides
identify()is virtual inShape, overridden inCircle, and again inColoredCircle.Step 2: Determine actual object type at runtime
The pointerptris of typeShape*but points to aColoredCircleobject, so the most derived override runs.Final Answer:
Colored Circle -> Option AQuick Check:
Most derived override called at runtime [OK]
- Expecting base or intermediate class output
- Thinking multiple overrides cause errors
- Ignoring virtual override chain
Ready to prove it?
Pass the test and this pattern moves unknown
