Bird
Raised Fist0
C++programming~20 mins

Why polymorphism is needed in C++ - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Polymorphism Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use polymorphism in C++?

Imagine you have different types of animals, each can make a sound. Why is polymorphism useful in this case?

C++
class Animal {
public:
    virtual void makeSound() {
        std::cout << "Some generic sound" << std::endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "Bark" << std::endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "Meow" << std::endl;
    }
};

void playSound(Animal* animal) {
    animal->makeSound();
}

int main() {
    Dog dog;
    Cat cat;
    playSound(&dog);
    playSound(&cat);
    return 0;
}
AIt makes the program run faster by avoiding function calls.
BIt forces all animals to have the same sound, so code is simpler.
CIt prevents creating objects of different animal types.
DIt allows calling the correct makeSound() method for each animal type using a single interface.
Attempts:
2 left
πŸ’‘ Hint

Think about how you can use one function to handle many animal types and get different sounds.

❓ Predict Output
intermediate
1:30remaining
What is the output of this polymorphism example?

Look at the code below. What will it print?

C++
class Base {
public:
    virtual void show() { std::cout << "Base" << std::endl; }
};

class Derived : public Base {
public:
    void show() override { std::cout << "Derived" << std::endl; }
};

int main() {
    Base* b = new Derived();
    b->show();
    delete b;
    return 0;
}
ABase
BRuntime error
CDerived
DCompilation error
Attempts:
2 left
πŸ’‘ Hint

Remember virtual functions decide which method to call at runtime based on the actual object.

πŸ”§ Debug
advanced
2:30remaining
Why does this polymorphism code cause a problem?

Find the error in this code and what problem it causes.

C++
class Animal {
public:
    void makeSound() { std::cout << "Animal sound" << std::endl; }
};

class Dog : public Animal {
public:
    void makeSound() { std::cout << "Bark" << std::endl; }
};

int main() {
    Animal* a = new Dog();
    a->makeSound();
    delete a;
    return 0;
}
AThe output is "Animal sound" because makeSound() is not virtual, so Dog's method is not called.
BThe program crashes because of a missing virtual destructor.
CCompilation error due to missing override keyword.
DDog's makeSound() is called correctly, so output is "Bark".
Attempts:
2 left
πŸ’‘ Hint

Check if the base class method is virtual to enable polymorphism.

πŸ“ Syntax
advanced
1:30remaining
Which option correctly declares a polymorphic base class?

Choose the correct way to declare a base class with a virtual function for polymorphism.

Aclass Shape { public: void draw() { /*...*/ } };
Bclass Shape { public: virtual void draw() { /*...*/ } };
Cclass Shape { public: virtual void draw() = 0; };
Dclass Shape { public: void virtual draw() { /*...*/ } };
Attempts:
2 left
πŸ’‘ Hint

Remember the correct syntax for virtual functions in C++.

πŸš€ Application
expert
3:00remaining
How many objects are created and which method is called?

Analyze the code below. How many objects are created and what is printed?

C++
class Vehicle {
public:
    virtual void start() { std::cout << "Vehicle starts" << std::endl; }
    virtual ~Vehicle() {}
};

class Car : public Vehicle {
public:
    void start() override { std::cout << "Car starts" << std::endl; }
};

int main() {
    Vehicle* v1 = new Vehicle();
    Vehicle* v2 = new Car();
    v1->start();
    v2->start();
    delete v1;
    delete v2;
    return 0;
}
ATwo objects created; output: Vehicle starts\nCar starts
BTwo objects created; output: Car starts\nCar starts
COne object created; output: Vehicle starts\nVehicle starts
DCompilation error due to missing destructor
Attempts:
2 left
πŸ’‘ Hint

Count the new statements and check which start() method is called for each pointer.

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