Inheritance and polymorphism reduce code redundancy in C++ in the following ways: Inheritance: Derived classes inherit members of the base class to avoid repeatedly defining common code. Polymorphism: Different derived class objects respond to different behaviors with the same function call, without using if-else statements to check types.
#How do inheritance and polymorphism in C++ reduce code redundancy?
Introduction
Inheritance and polymorphism are powerful tools in C++ for reusing code and reducing redundancy. Through inheritance, a derived class can inherit data members and methods from a base class. Polymorphism allows objects of a derived class to respond to the same function call in different ways.
Practical case: graphics library
Consider a simple graphics library that contains a hierarchy of classes for drawing different shapes.
class Shape { public: virtual void draw() = 0; // 纯虚函数 }; class Circle : public Shape { public: void draw() override { // 绘制圆形 } }; class Rectangle : public Shape { public: void draw() override { // 绘制矩形 } }; class Triangle : public Shape { public: void draw() override { // 绘制三角形 } };
Inheritance
By using inheritance, we avoid repeating the draw
method for each shape. Instead, a derived class simply overrides the draw
method and provides its own implementation of drawing the shape.
Polymorphism
Polymorphism allows us to use Shape
objects in a polymorphic manner. This means that we can create an array containing objects of different shapes and draw them by simply calling the draw
method. C++ will automatically call the correct draw
method of the derived class.
Shape* shapes[] = {new Circle(), new Rectangle(), new Triangle()}; for (Shape* shape : shapes) { shape->draw(); // 调用正确派生类的 draw 方法 }
Reduce redundancy
By using inheritance and polymorphism, we significantly reduce code redundancy.
draw
method for each shape. if-else
statements are no longer needed to determine the shape type. Advantages
Conclusion
Inheritance and polymorphism in C++ are powerful tools for reducing code redundancy and creating flexible and extensible code bases.
The above is the detailed content of How do inheritance and polymorphism reduce code redundancy in C++?. For more information, please follow other related articles on the PHP Chinese website!