๐ Scenario: You are creating a simple program to demonstrate how different animals make different sounds. Each animal has a method to make a sound, but the exact sound depends on the animal type.
๐ฏ Goal: Build a C++ program that uses runtime polymorphism to call the correct makeSound() method for different animal objects.
๐ What You'll Learn
Create a base class called Animal with a virtual method makeSound().
Create two derived classes Dog and Cat that override makeSound().
Use a pointer of type Animal* to call makeSound() on objects of Dog and Cat.
Print the sounds made by the dog and cat.
๐ก Why This Matters
๐ Real World
Runtime polymorphism helps programs decide which method to run while the program is running, like choosing the right animal sound depending on the animal.
๐ผ Career
Understanding runtime polymorphism is essential for writing flexible and maintainable object-oriented code used in software development jobs.
Progress0 / 4 steps
1
Create the base class Animal
Write a class called Animal with a public virtual method makeSound() that prints "Some generic animal sound".
C++
Hint
Use virtual keyword before makeSound() to allow overriding.
2
Create derived classes Dog and Cat
Add two classes Dog and Cat that inherit from Animal. Override makeSound() in Dog to print "Woof!" and in Cat to print "Meow!".
C++
Hint
Use override keyword to clearly show you are overriding the base class method.
3
Use Animal pointers to call makeSound()
Create two pointers of type Animal*, one pointing to a Dog object and the other to a Cat object. Use these pointers to call makeSound().
C++
Hint
Use new to create objects and call makeSound() through pointers.
4
Print the sounds made by Dog and Cat
Add cout statements to print the sounds made by the dog and cat when calling makeSound(). Run the program to see the output.
C++
Hint
Running the program should print Woof! and Meow! on separate lines.
Practice
(1/5)
1. What is the main purpose of virtual functions in C++ runtime polymorphism?
easy
A. To allocate memory for objects dynamically
B. To make functions run faster by avoiding function calls
C. To prevent any function from being overridden in derived classes
D. To allow derived classes to override base class methods and decide at runtime which method to call
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 D