Home > Article > Backend Development > How to override base class function in C++?
In C, function overriding allows a derived class to override a base class function to extend or modify its behavior. The syntax is: Have the same function name Have the same function signature Use the override keyword
Comprehensive guide to function rewriting in C
In C, function overriding allows derived classes to override functions in base classes. This is useful when extending base class functionality or modifying its behavior.
Syntax
To override a base class function, the function in the derived class must:
override
keyword For example, consider the following base class:
class Base { public: virtual void print() { std::cout << "Base class" << std::endl; } };
To override the print()
function, derived classes can use the following syntax:
class Derived : public Base { public: override void print() { std::cout << "Derived class" << std::endl; } };
Practical case
Consider a Shape
base class and a Circle
derived class:
class Shape { public: virtual double area() { return 0; } }; class Circle : public Shape { public: double radius; override double area() { return 3.14 * radius * radius; } };
In the main()
function, we can use virtual method scheduling to call these two methods :
int main() { // 创建一个圆形对象 Circle circle; circle.radius = 5; // 通过基类指针调用派生类函数 Shape* shape = &circle; double area = shape->area(); std::cout << "Area of the circle: " << area << std::endl; return 0; }
Output:
Area of the circle: 78.5
The above is the detailed content of How to override base class function in C++?. For more information, please follow other related articles on the PHP Chinese website!