Bird
Raised Fist0
C++programming~10 mins

Why polymorphism is needed in C++ - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why polymorphism is needed
Define base class pointer
↓
Assign derived class object
↓
Call virtual function
↓
Derived class function runs
↓
Program behaves correctly for different types
↓
END
Polymorphism lets a program decide at runtime which function to run, so one pointer can work with many types and call the right function.
Execution Sample
C++
#include <iostream>
using namespace std;

class Animal {
public:
  virtual void sound() { cout << "Animal sound"; }
};
class Dog : public Animal {
public:
  void sound() override { cout << "Bark"; }
};

int main() {
  Animal* a = new Dog();
  a->sound();
  delete a;
  return 0;
}
This code shows a base class pointer pointing to a derived class object and calling the correct overridden function.
Execution Table
StepPointer TypeObject TypeFunction CalledOutput
1Animal*DogDog::sound()Bark
2Animal*AnimalAnimal::sound()Animal sound
3Animal*DogDog::sound()Bark
4END--Program ends
💡 Program ends after calling the correct function based on object type at runtime.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
a (Animal*)nullpoints to Dog objectpoints to Dog objectpoints to Dog object
Key Moments - 2 Insights
Why does the Dog's sound() run instead of Animal's when using an Animal pointer?
Because the function is virtual, the program checks the actual object type at runtime and calls Dog's sound(), as shown in execution_table step 1.
What if sound() was not virtual? Which function would run?
If sound() was not virtual, Animal's sound() would run even if the pointer points to Dog, shown by comparing step 2 in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what function is called at step 1?
AAnimal::sound()
BNo function called
CDog::sound()
DCompiler error
💡 Hint
Check the 'Function Called' column in execution_table row for step 1.
At which step does the Animal::sound() function run?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Function Called' column in execution_table for Animal::sound().
If sound() was not virtual, what would happen at step 1?
AAnimal::sound() runs
BDog::sound() runs
CProgram crashes
DNo output
💡 Hint
Refer to key_moments explanation about virtual function behavior.
Concept Snapshot
Polymorphism allows one pointer to call different functions based on object type.
Use virtual functions in base class.
Derived classes override these functions.
At runtime, correct function runs.
Without virtual, base class function always runs.
This enables flexible and reusable code.
Full Transcript
Polymorphism is needed so that a program can decide which function to run based on the actual object type at runtime. In C++, this is done using virtual functions. A base class pointer can point to different derived class objects. When calling a virtual function through this pointer, the program runs the derived class's version, not the base class's. This behavior allows writing flexible code that works correctly with many types. If the function is not virtual, the base class version always runs, which is usually not what we want. The example shows an Animal pointer pointing to a Dog object. Calling sound() runs Dog's sound(), printing 'Bark'. This is polymorphism in action.

Practice

(1/5)
1. Why is polymorphism important in C++ programming?
easy
A. It allows one interface to work with different object types.
B. It makes the program run faster by using less memory.
C. It prevents any changes to the code once compiled.
D. It forces all functions to have the same name.

Solution

  1. Step 1: Understand polymorphism concept

    Polymorphism means one interface can represent many forms or object types.
  2. Step 2: Identify the benefit in code flexibility

    This allows calling the correct function automatically depending on the object type, making code flexible and reusable.
  3. Final Answer:

    It allows one interface to work with different object types. -> Option A
  4. Quick Check:

    Polymorphism = One interface, many types [OK]
Hint: Polymorphism means many forms, one interface [OK]
Common Mistakes:
  • Thinking polymorphism improves speed directly
  • Confusing polymorphism with code immutability
  • Believing polymorphism forces identical function names
2. Which of the following is the correct way to declare a virtual function in C++?
easy
A. void virtual func();
B. void func() virtual;
C. virtual void func();
D. virtual func void();

Solution

  1. Step 1: Recall virtual function syntax

    In C++, the keyword 'virtual' comes before the return type in the function declaration.
  2. Step 2: Match correct syntax

    Only 'virtual void func();' matches the correct syntax for declaring a virtual function.
  3. Final Answer:

    virtual void func(); -> Option C
  4. Quick Check:

    Virtual keyword before return type [OK]
Hint: Virtual keyword always precedes return type [OK]
Common Mistakes:
  • Placing 'virtual' after function name
  • Mixing order of keywords
  • Omitting parentheses in declaration
3. What will be the output of the following C++ code?
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;
}
medium
A. Runtime error
B. Base
C. Compilation error
D. Derived

Solution

  1. Step 1: Understand virtual function behavior

    The 'show' function is virtual in Base and overridden in Derived, so the call uses Derived's version.
  2. Step 2: Analyze pointer type and object

    Pointer is Base* but points to Derived object, so ptr->show() calls Derived::show(), printing "Derived".
  3. Final Answer:

    Derived -> Option D
  4. Quick Check:

    Virtual function calls Derived version [OK]
Hint: Virtual calls use actual object type, not pointer type [OK]
Common Mistakes:
  • Assuming Base version prints because pointer type is Base*
  • Confusing override keyword effect
  • Ignoring virtual function behavior
4. Identify the error in this C++ code related to polymorphism:
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;
}
medium
A. Missing virtual keyword in base class function.
B. Dog class should not inherit from Animal.
C. Pointer type should be Dog*, not Animal*.
D. sound() function should return a string.

Solution

  1. Step 1: Check function declaration in base class

    The base class function 'sound' is not declared virtual, so polymorphism won't work.
  2. Step 2: Understand effect on function call

    Because 'sound' is not virtual, calling a->sound() calls Animal::sound(), not Dog::sound().
  3. Final Answer:

    Missing virtual keyword in base class function. -> Option A
  4. Quick Check:

    Base function must be virtual for polymorphism [OK]
Hint: Base class functions must be virtual for polymorphism [OK]
Common Mistakes:
  • Thinking inheritance alone enables polymorphism
  • Using wrong pointer type for polymorphism
  • Expecting return type change to fix polymorphism
5. You want to design a system where different shapes (Circle, Square) can be drawn using the same interface. Which approach best uses polymorphism in C++?
hard
A. Define draw() as a static method in each shape class.
B. Create a base class Shape with a virtual draw() method, and override draw() in Circle and Square classes.
C. Use global functions drawCircle() and drawSquare() without classes.
D. Create separate classes Circle and Square without any base class and call their draw() directly.

Solution

  1. Step 1: Identify polymorphism design pattern

    Polymorphism requires a common interface with virtual functions to allow different behaviors.
  2. Step 2: Match design to polymorphism

    Base class Shape with virtual draw() lets Circle and Square override draw(), enabling polymorphic calls.
  3. Final Answer:

    Create a base class Shape with a virtual draw() method, and override draw() in Circle and Square classes. -> Option B
  4. Quick Check:

    Virtual base method with overrides enables polymorphism [OK]
Hint: Use virtual base method and override in derived classes [OK]
Common Mistakes:
  • Not using a base class for common interface
  • Using static methods which don't support polymorphism
  • Using separate global functions instead of class methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard