Home >Backend Development >C++ >C++ function rewriting: Uncovering the secrets of behavior coverage in inheritance
Function rewriting occurs when a derived class defines a function with the same name and implements it differently. Rules include: Use the override keyword. The name, parameters, and return type are the same as the base class function. Access rights must be no lower than those of base class functions. Through overriding, derived classes can override base class behavior, achieve polymorphism, and dynamically call methods of the same name in different derived classes.
In C, function rewriting is a way to achieve polymorphic behavior through inheritance key features. Function overriding occurs when a derived class defines a function with the same name as its base class but with a different implementation.
In order to override a base class function, the derived class must use the override
keyword. For example:
class Base { public: virtual void print() { cout << "Base class print()" << endl; } }; class Derived : public Base { public: virtual void print() override { cout << "Derived class print()" << endl; } };
The rules for function rewriting are as follows:
override
keyword. Consider a shape abstract class and its two derived classes rectangle and circle.
class Shape { public: virtual double getArea() = 0; }; class Rectangle : public Shape { public: double width, height; Rectangle(double w, double h) : width(w), height(h) {} override double getArea() { return width * height; } }; class Circle : public Shape { public: double radius; Circle(double r) : radius(r) {} override double getArea() { return M_PI * radius * radius; } }; int main() { Rectangle rect(5, 3); Circle circle(4); Shape* shapes[] = {&rect, &circle}; for (auto shape : shapes) { cout << "Shape area: " << shape->getArea() << endl; } }
In this example, the Shape
class defines an abstract method getArea()
, derived from classes Rectangle
and Circle
Rewritten to provide actual area calculations. Through polymorphism, we can dynamically calculate and output the areas of different shapes by calling the getArea()
method using the base class pointer in the shapes
array.
The above is the detailed content of C++ function rewriting: Uncovering the secrets of behavior coverage in inheritance. For more information, please follow other related articles on the PHP Chinese website!