Virtual Function in OOP - Explanation (10 Marks)
Definition:
A virtual function in C++ is a member function in the base class that you expect to override in
derived classes.
It is declared using the keyword 'virtual'. The main purpose is to achieve runtime polymorphism,
allowing the
correct function to be called for an object, regardless of the type of reference (or pointer) used.
Key Features:
- Declared using the keyword virtual in the base class.
- Supports dynamic (runtime) binding instead of static (compile-time) binding.
- Enables function overriding in derived classes.
- Can only be accessed via a pointer or reference to the base class.
- Used for polymorphic behavior.
Syntax:
class Base {
public:
virtual void display(); // Virtual function
};
Program Example:
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound" << endl;
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
};
int main() {
Animal* animal;
Dog d;
Cat c;
animal = &d;
animal->sound(); // Calls Dog's sound()
animal = &c;
animal->sound(); // Calls Cat's sound()
return 0;
Output:
Dog barks
Cat meows
Explanation of Program:
- A virtual function 'sound()' is declared in the base class Animal.
- It is overridden in the derived classes Dog and Cat.
- A base class pointer 'animal' is used to point to objects of Dog and Cat.
- Due to virtual function and dynamic binding, the correct function is called at runtime.
Advantages:
- Supports polymorphism.
- Improves code reusability and flexibility.
- Allows function overriding to work correctly with base class pointers.