Home > Article > Backend Development > What role do virtual functions play in polymorphism in C++?
Polymorphism is achieved through dynamic binding. Virtual functions allow derived class objects to call their own versions of virtual functions, even if the function is declared by the base class. Specifically: virtual functions are declared in the base class and use the virtual keyword. The compiler uses a virtual pointer table to dynamically look up the function implementation for the runtime object type. A derived class object always calls its own version of a virtual function, even if it is declared by a base class.
The role of virtual functions in C++ polymorphism
In object-oriented programming (OOP), polymorphism is A characteristic that allows an object to respond to the same method call in different ways. In C++, virtual functions achieve polymorphism through dynamic binding.
What is a virtual function?
Virtual functions are member functions declared in the base class and overridden by the derived class. When declaring virtual functions in a base class, use the virtual
keyword prefix.
How virtual functions work
When a virtual function is called, the compiler does not look for the function implementation in the base class. Instead, it looks for the function implementation for the runtime object type. This means that a subclass object always calls its own version of a virtual function, even if the function is declared by the base class.
Virtual pointer table
Virtual function calls involve a special data structure called a virtual pointer table. For each class with virtual functions, the compiler creates a virtual pointer table that contains pointers to the virtual functions of the class. When a derived class object is created, the object contains a pointer to its own virtual pointer table.
Practical case
Consider the following example:
class Shape { public: virtual void draw() const = 0; // 其他函数和变量 }; class Rectangle : public Shape { public: void draw() const override { // 绘制一个矩形 } }; class Circle : public Shape { public: void draw() const override { // 绘制一个圆 } }; int main() { Shape* shapes[] = {new Rectangle(), new Circle()}; for (Shape* shape : shapes) { shape->draw(); // 根据运行时类型调用正确的 draw() 方法 delete shape; } }
In this example, the Shape
class declares a virtual functiondraw()
. Derived classes Rectangle
and Circle
override the draw()
method to provide custom implementations for specific shapes. In the main()
function, we create an array of shapes and call the draw()
method on each shape. Although all shapes are declared as base class types, they call the correct draw()
method based on the actual runtime type, demonstrating the power of virtual functions to achieve polymorphism in C++.
The above is the detailed content of What role do virtual functions play in polymorphism in C++?. For more information, please follow other related articles on the PHP Chinese website!