Virtual functions in C allow derived classes to redefine methods inherited from base classes to achieve polymorphism. The syntax is: declare a virtual function with the virtual keyword in the base class, and redefine it with override in the derived class. By calling a virtual function through a pointer or reference, a derived class object can call a base class virtual function. The main functions of virtual functions include: realizing polymorphism, supporting dynamic binding and providing abstraction.
Virtual function in C
Introduction
Virtual function is a A special type of member function that allows a derived class to redefine methods inherited from a base class. This enables polymorphism, i.e. derived class objects can be treated in the same way as base class objects.
Syntax
Virtual functions are declared in the base class, using the virtual
keyword:
class Base { public: virtual void func() { /* ... */ } };
In the derived class, Virtual functions can be redefined:
class Derived : public Base { public: void func() override { /* ... */ } };
Virtual function calls are completed through pointers or references, so derived class objects can call virtual functions in the parent class:
Base* base = new Derived; base->func(); // 调用 Derived::func()
Practical case
Consider the following example:
class Shape { public: virtual double area() const = 0; }; class Circle : public Shape { public: Circle(double radius) : _radius(radius) {} double area() const override { return _radius * _radius * 3.14; } double _radius; }; class Square : public Shape { public: Square(double side) : _side(side) {} double area() const override { return _side * _side; } double _side; }; int main() { Shape* shapes[] = {new Circle(5), new Square(4)}; double total_area = 0; for (Shape* shape : shapes) { total_area += shape->area(); } std::cout << "Total area: " << total_area << std::endl; }
In this example, the base class Shape
defines an abstract function area()
, and the derived class Circle
and Square
provide their own implementations. The main function creates an array of Shape
pointers pointing to objects of the derived class, and calculates the total area through virtual function calls.
Function
The main functions of virtual functions include:
The above is the detailed content of Can a C++ function be declared virtual? What is the role of virtual functions?. For more information, please follow other related articles on the PHP Chinese website!