Virtual functions let a program choose the right function to run when using a base class pointer or reference. This helps when you want different behaviors for different types of objects.
Virtual functions in C++
class Base { public: virtual void functionName(); };
The keyword virtual before a function means it can be overridden in derived classes.
Virtual functions must be members of a class.
sound that can be changed in derived classes.class Animal { public: virtual void sound() { std::cout << "Some sound" << std::endl; } };
Dog overrides the virtual function to provide its own behavior.class Dog : public Animal { public: void sound() override { std::cout << "Bark" << std::endl; } };
Dog version of sound because it is virtual.#include <iostream> int main() { Animal* a = new Dog(); a->sound(); delete a; return 0; }
This program shows how virtual functions let the program call the right sound function depending on the actual object type, even when using base class pointers.
#include <iostream> class Animal { public: virtual void sound() { std::cout << "Some sound" << std::endl; } virtual ~Animal() = default; }; class Dog : public Animal { public: void sound() override { std::cout << "Bark" << std::endl; } }; class Cat : public Animal { public: void sound() override { std::cout << "Meow" << std::endl; } }; int main() { Animal* animal1 = new Dog(); Animal* animal2 = new Cat(); animal1->sound(); // Calls Dog's sound animal2->sound(); // Calls Cat's sound delete animal1; delete animal2; return 0; }
If a function is not virtual, the base class version is called even if the pointer points to a derived object.
Use override keyword in derived classes to help catch mistakes.
Remember to make destructors virtual if you use virtual functions to avoid memory leaks.
Virtual functions allow dynamic choice of function at runtime based on object type.
They enable polymorphism, making code flexible and reusable.
Always use virtual in base class and override in derived classes for clarity.
Practice
virtual in a C++ base class?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 AQuick Check:
Virtual function = runtime polymorphism [OK]
- Confusing virtual with inline functions
- Thinking virtual prevents overriding
- Assuming virtual makes function static
display in a base class?Solution
Step 1: Recall correct virtual function syntax
The keywordvirtualmust come before the return type and function name.Step 2: Check each option
virtual void display(); correctly placesvirtualbeforevoid display();. Others have incorrect order or placement.Final Answer:
virtual void display(); -> Option AQuick Check:
virtual before return type = correct syntax [OK]
- Placing virtual after function name
- Mixing order of keywords
- Adding virtual at the end of declaration
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?
Solution
Step 1: Analyze pointer and object types
The pointer is of typeBase*but points to aDerivedobject.Step 2: Understand virtual function call
Becauseshow()is virtual, theDerivedversion is called at runtime, printing "Derived".Final Answer:
Derived -> Option CQuick Check:
Virtual function calls derived version [OK]
- Assuming base class function runs
- Confusing override keyword effect
- Expecting compilation or runtime errors
class Base {
public:
void display() { std::cout << "Base"; }
};
class Derived : public Base {
public:
void display() override { std::cout << "Derived"; }
};Solution
Step 1: Check base class function declaration
The base class functiondisplay()is not declaredvirtual.Step 2: Understand override keyword usage
Theoverridekeyword 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 DQuick Check:
Override needs virtual base function [OK]
- Ignoring missing virtual in base
- Thinking override is optional
- Assuming same name always means override
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;
}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
Callingsound()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 BQuick Check:
Virtual calls print actual object sounds [OK]
- Expecting base class sound for all
- Confusing array pointer syntax
- Assuming compilation error with polymorphism
Ready to prove it?
Pass the test and this pattern moves unknown
