Home >Backend Development >C++ >C++ function rewriting in practice: a trick to implement subclass-specific functions
Function rewriting allows subclasses to redefine functions of the same name of the base class to implement functions specific to the subclass: based on name lookup and type matching, when a subclass defines a function of the same name, the base class function will be rewritten. This allows subclasses to provide different implementations, for example the Circle and Rectangle classes in the example override the area() function of the Shape class to calculate their own area.
C Function rewriting: Implementation of subclass-specific functions
Function rewriting is an important mechanism in C. It allows subclasses to redefine the behavior of functions of the same name in the base class. This is useful for defining specific functionality specific to a subclass.
Principle
Function rewriting is based on name lookup and type matching rules. When a function is called, the compiler searches the scope for a function with a matching name. If multiple overloaded functions are found, the best match principle is used for selection.
If the subclass defines a function with the same name as the base class, the function in the subclass will override the function in the base class. This allows subclasses to provide a different implementation than the base class.
Practical case
Consider a scenario where we have a Shape
base class that represents a general shape. Derived classes Circle
and Rectangle
represent circles and rectangles respectively. We need to calculate the area of these shapes.
Base class Shape
class Shape { public: virtual double area() const = 0; // 纯虚函数 };
Derived class Circle
class Circle : public Shape { public: Circle(double radius) : radius(radius) {} double area() const override { return M_PI * radius * radius; } private: double radius; };
Derived class Rectangle
class Rectangle : public Shape { public: Rectangle(double width, double height) : width(width), height(height) {} double area() const override { return width * height; } private: double width, height; };
Using
We can use these classes to calculate the area of different shapes:
int main() { Circle circle(5.0); Rectangle rectangle(3.0, 4.0); std::cout << "Area of circle: " << circle.area() << std::endl; std::cout << "Area of rectangle: " << rectangle.area() << std::endl; return 0; }
Output:
Area of circle: 78.5398 Area of rectangle: 12.0
In this example, The Circle
and Rectangle
classes override the area()
function defined in the Shape
class. This allows us to implement area calculation logic specific to each shape.
The above is the detailed content of C++ function rewriting in practice: a trick to implement subclass-specific functions. For more information, please follow other related articles on the PHP Chinese website!