Virtual Functions
Virtual functions are a fundamental concept in object-oriented programming that enable polymorphism. They allow you to redefine the behavior of a function in derived classes, providing flexibility and dynamic binding.
Syntax:
virtual return_type function_name();
How it Works:
When a virtual function is called on a pointer or reference to a base class object, the actual function to be executed is determined at runtime based on the dynamic type of the object.
This process is known as late binding or dynamic dispatch.
Example:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() {
cout << "Drawing a shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing a circle" << endl;
}
};
class Square : public Shape {
public:
void draw() override {
cout << "Drawing a square" << endl;
}
};
int main() {
Shape *shapePtr;
shapePtr = new Circle();
shapePtr->draw(); // Output: Drawing a circle
shapePtr = new Square();
shapePtr->draw(); // Output: Drawing a square
return 0;
}
Pure Virtual Functions
A pure virtual function is a virtual function declared with = 0. It doesn't have an implementation in the base class, making the base class abstract. Derived classes must provide their own implementation for these functions.
Syntax:
virtual return_type function_name() = 0;
Example:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
// ... (Same as the previous example)
Key Points:
Virtual functions allow for polymorphic behavior, where different derived classes can provide different implementations of the same function.
Pure virtual functions make a class abstract, meaning it cannot be instantiated directly.
Abstract classes serve as base classes for derived classes, providing a common interface.
By using virtual and pure virtual functions, you can create flexible and extensible object-oriented designs.
Comentários