In C++, a virtual function is a member function of a class that can be overridden in derived classes. Virtual functions are used in the context of polymorphism, which allows objects of different classes to be treated as objects of a common base class. This enables dynamic binding, meaning that the appropriate function to call is determined at runtime based on the actual derived class of the object.
Here's an example:
cpp#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* shape1 = new Circle();
Shape* shape2 = new Square();
shape1->draw(); // Calls Circle's draw
shape2->draw(); // Calls Square's draw
delete shape1;
delete shape2;
return 0;
}
In this example, the
draw
function is declared as virtual in the base class Shape
, and it is overridden in the derived classes Circle
and Square
. When we call draw
on a base class pointer that points to a derived class object, the appropriate overridden function is called at runtime.
No comments:
Post a Comment