🧩 Inheritance & Polymorphism with Virtual Functions in C++
Inheritance and polymorphism are fundamental concepts in C++'s object-oriented programming. Virtual functions enable polymorphic behavior, allowing derived classes to override base class methods dynamically at runtime.
📘 What is Inheritance?
Inheritance allows a class (derived class) to inherit properties and behaviors (methods) from another class (base class). This promotes code reuse and hierarchical relationships between classes.
📘 What is Polymorphism?
Polymorphism means "many forms". It allows a base class pointer or reference to refer to objects of derived classes and call the appropriate overridden methods. This is primarily achieved using virtual functions in C++.
💡 Why Use Virtual Functions?
- Enable dynamic (runtime) method binding instead of static (compile-time).
- Allow derived classes to provide their own implementation of base class functions.
- Essential for flexible and extendable code design.
📄 C++ Example: Inheritance, Polymorphism, Virtual Functions
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { // Virtual function
cout << "Animal makes a sound" << endl;
}
virtual ~Animal() {} // Virtual destructor
};
class Dog : public Animal {
public:
void sound() override { // Override base class function
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
void makeSound(Animal *a) {
a->sound(); // Calls the appropriate derived class function at runtime
}
int main() {
Animal *animal1 = new Dog();
Animal *animal2 = new Cat();
makeSound(animal1); // Dog barks
makeSound(animal2); // Cat meows
delete animal1;
delete animal2;
return 0;
}
📝 Sample Output
Cat meows
🧠 How It Works
Animal
is the base class with a virtual functionsound()
.Dog
andCat
override thesound()
method.- Using a base class pointer to derived objects enables polymorphism.
- The virtual function mechanism ensures the correct derived method is called at runtime.
- Virtual destructor ensures proper cleanup when deleting derived objects via base pointers.
This technique allows your programs to be more flexible and extendable without changing existing code — a cornerstone of object-oriented design.
Post a Comment