Virtual Functions and Pointers
Virtual functions and pointers are core concepts in C++ that enable runtime polymorphism, allowing programs to achieve flexible and dynamic behavior.
- Virtual Functions
A virtual function is a member function in a base class that can be overridden in a derived class. It is declared using the virtual keyword and allows the program to resolve function calls at runtime rather than compile-time—a technique known as dynamic dispatch.
- Key Features:
- Enables runtime polymorphism
- Must be accessed through a pointer or reference to the base class
- Allows derived classes to provide specific implementations
- Pointers and Virtual Functions
When a base class pointer points to an object of a derived class, and a virtual function is called through this pointer, C++ will invoke the derived class version of the function—even if the pointer’s type is the base class. This behavior is essential for designing flexible and extensible systems.
Example:
class Base {
public:
virtual void show() {
cout << “Base class display\n”;
}
};
class Derived : public Base {
public:
void show() override {
cout << “Derived class display\n”;
}
};
int main() {
Base* ptr;
Derived d;
ptr = &d;
ptr->show(); // Outputs: Derived class display
}
Abstract Classes and Pure Virtual Functions
An abstract class is one that contains at least one pure virtual function. It cannot be instantiated directly and acts as a blueprint for derived classes.
General Syntax:
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
Example:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
cout << “Drawing Circle” << endl;
}
};
int main() {
Shape* s = new Circle();
s->draw();
delete s;
return 0;
}