Imagine you have different types of animals, each can make a sound. Why is polymorphism useful in this case?
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; }
Think about how you can use one function to handle many animal types and get different sounds.
Polymorphism lets us use a single interface (like a pointer to Animal) to call the right method for each specific animal type (Dog, Cat). This makes code flexible and easier to extend.
Look at the code below. What will it print?
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; }
Remember virtual functions decide which method to call at runtime based on the actual object.
The pointer b is of type Base*, but it points to a Derived object. Because show() is virtual, Derived's show() is called, printing "Derived".
Find the error in this code and what problem it causes.
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; }
Check if the base class method is virtual to enable polymorphism.
Without virtual keyword, the base class method is called even if the pointer points to a derived object. So output is "Animal sound" instead of "Bark".
Choose the correct way to declare a base class with a virtual function for polymorphism.
Remember the correct syntax for virtual functions in C++.
Option B correctly declares a virtual function with a body. Option B is a pure virtual function (abstract), which is valid but different. Option B has wrong syntax. Option B is not virtual.
Analyze the code below. How many objects are created and what is printed?
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; }
Count the new statements and check which start() method is called for each pointer.
Two objects are created: one Vehicle and one Car. The first pointer calls Vehicle::start(), the second calls Car::start() because of virtual function.