๐ Scenario: Imagine you are creating a simple program to manage different types of animals and their sounds. Each animal can make a sound, but the exact sound depends on the animal type.
๐ฏ Goal: You will build a small C++ program using classes and virtual functions to show how different animals make different sounds when called through a base class pointer.
๐ What You'll Learn
Create a base class called Animal with a virtual function makeSound().
Create two derived classes called Dog and Cat that override the makeSound() function.
Use a pointer of type Animal* to call the makeSound() function on objects of Dog and Cat.
Print the sounds made by the animals to the console.
๐ก Why This Matters
๐ Real World
Virtual functions are used in software where different objects share a common interface but have different behaviors, like in games, simulations, or user interface toolkits.
๐ผ Career
Understanding virtual functions is essential for C++ developers working on object-oriented design, enabling flexible and maintainable code.
Progress0 / 4 steps
1
Create the base class Animal
Write a class called Animal with a public virtual function makeSound() that prints "Some generic animal sound".
C++
Hint
Use the keyword virtual before the function makeSound() inside the Animal class.
2
Create derived classes Dog and Cat
Add two classes called Dog and Cat that inherit from Animal. Override the makeSound() function in Dog to print "Woof!" and in Cat to print "Meow!".
C++
Hint
Use class Dog : public Animal and class Cat : public Animal. Use override keyword for makeSound().
3
Use Animal pointers to call makeSound()
Create two pointers of type Animal* named dogPtr and catPtr. Point dogPtr to a new Dog object and catPtr to a new Cat object. Call makeSound() using both pointers.
C++
Hint
Use Animal* dogPtr = new Dog(); and call dogPtr->makeSound();.
4
Print the sounds made by Dog and Cat
Run the program and print the output of calling makeSound() on dogPtr and catPtr. The output should show the correct sounds for Dog and Cat.
C++
Hint
Run the program and check that the output matches exactly Woof! and Meow! on separate lines.
Practice
(1/5)
1. What is the main purpose of declaring a function as virtual in a C++ base class?
easy
A. To allow derived classes to override the function and enable runtime polymorphism
B. To make the function inline for faster execution
C. To prevent the function from being overridden in derived classes
D. To make the function static and shared among all objects
Solution
Step 1: Understand virtual function role
A virtual function in a base class allows derived classes to provide their own implementation that will be called at runtime.
Step 2: Recognize runtime polymorphism
This mechanism enables dynamic dispatch, meaning the program decides which function to call based on the actual object type, not the pointer type.
Final Answer:
To allow derived classes to override the function and enable runtime polymorphism -> Option A
Quick Check:
Virtual function = runtime polymorphism [OK]
Hint: Virtual means choose function at runtime, not compile time [OK]
Common Mistakes:
Confusing virtual with inline functions
Thinking virtual prevents overriding
Assuming virtual makes function static
2. Which of the following is the correct syntax to declare a virtual function named display in a base class?
easy
A. virtual void display();
B. void virtual display();
C. virtual display void();
D. void display() virtual;
Solution
Step 1: Recall correct virtual function syntax
The keyword virtual must come before the return type and function name.
Step 2: Check each option
virtual void display(); correctly places virtual before void display();. Others have incorrect order or placement.
Final Answer:
virtual void display(); -> Option A
Quick Check:
virtual before return type = correct syntax [OK]
Hint: Put 'virtual' before return type in function declaration [OK]
Common Mistakes:
Placing virtual after function name
Mixing order of keywords
Adding virtual at the end of declaration
3. Consider the following 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;
}
What is the output when this program runs?
medium
A. Base
B. Runtime error
C. Derived
D. Compilation error
Solution
Step 1: Analyze pointer and object types
The pointer is of type Base* but points to a Derived object.
Step 2: Understand virtual function call
Because show() is virtual, the Derived version is called at runtime, printing "Derived".
Final Answer:
Derived -> Option C
Quick Check:
Virtual function calls derived version [OK]
Hint: Virtual calls use actual object type, not pointer type [OK]
Common Mistakes:
Assuming base class function runs
Confusing override keyword effect
Expecting compilation or runtime errors
4. Identify the error in the following code snippet:
class Base {
public:
void display() { std::cout << "Base"; }
};
class Derived : public Base {
public:
void display() override { std::cout << "Derived"; }
};
medium
A. Derived class function cannot have the same name as base class function
B. No error, code is correct
C. Override keyword is not allowed in derived class
D. Base class function must be declared virtual to allow override
Solution
Step 1: Check base class function declaration
The base class function display() is not declared virtual.
Step 2: Understand override keyword usage
The override keyword requires the base function to be virtual; otherwise, it causes a compilation error.
Final Answer:
Base class function must be declared virtual to allow override -> Option D
Quick Check:
Override needs virtual base function [OK]
Hint: Base function must be virtual to use override in derived [OK]
Common Mistakes:
Ignoring missing virtual in base
Thinking override is optional
Assuming same name always means override
5. Given the classes below, what will be the output of the program?
class Animal {
public:
virtual void sound() { std::cout << "Animal sound "; }
};
class Dog : public Animal {
public:
void sound() override { std::cout << "Bark "; }
};
class Cat : public Animal {
public:
void sound() override { std::cout << "Meow "; }
};
int main() {
Animal* animals[3];
animals[0] = new Animal();
animals[1] = new Dog();
animals[2] = new Cat();
for (int i = 0; i < 3; i++) {
animals[i]->sound();
}
for (int i = 0; i < 3; i++) {
delete animals[i];
}
return 0;
}
hard
A. Animal sound Animal sound Animal sound
B. Animal sound Bark Meow
C. Bark Meow Animal sound
D. Compilation error due to array of pointers
Solution
Step 1: Analyze array of Animal pointers
The array holds pointers to objects of types Animal, Dog, and Cat respectively.
Step 2: Understand virtual function calls in loop
Calling sound() on each pointer calls the overridden version based on actual object type, printing "Animal sound ", "Bark ", and "Meow ".
Final Answer:
Animal sound Bark Meow -> Option B
Quick Check:
Virtual calls print actual object sounds [OK]
Hint: Virtual functions call derived versions in arrays of base pointers [OK]
Common Mistakes:
Expecting base class sound for all
Confusing array pointer syntax
Assuming compilation error with polymorphism
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.