Home  >  Article  >  Backend Development  >  How to implement polymorphism in C++ class design?

How to implement polymorphism in C++ class design?

WBOY
WBOYOriginal
2024-06-03 19:23:00622browse

Polymorphism allows derived classes to have different behaviors while sharing the same interface. The steps to achieve this include: creating base classes, derived classes, virtual functions, and using base class pointers. The sample code shows how to use the shape class hierarchy. Structures (Shape, Rectangle, Circle) implement polymorphism and calculate the total area of ​​different shapes.

How to implement polymorphism in C++ class design?

Class design to implement polymorphism in C++

What is polymorphism?

Polymorphism allows derived classes to have different behaviors from base classes while sharing the same interface. It provides an elegant way to create collections of objects with similar behavior but different implementations.

Steps to achieve polymorphism:

  1. Creating a base class: Define a common interface that derived classes will share.
  2. Derived classes: Create derived classes from base classes to implement specific behaviors.
  3. Virtual function: Declare a virtual function in the base class and redefine it in the derived class. This allows function calls to be dynamically bound at runtime.
  4. Base class pointer: Use base class pointer or reference to hold derived class objects to achieve polymorphism.

Practical case:

Consider a hierarchy of shape classes:

class Shape {
public:
    virtual double area() = 0; // 纯虚函数(必须在派生类中重新定义)
};

class Rectangle : public Shape {
public:
    Rectangle(double width, double height) : width_(width), height_(height) {}
    double area() override { return width_ * height_; }
private:
    double width_;
    double height_;
};

class Circle : public Shape {
public:
    Circle(double radius) : radius_(radius) {}
    double area() override { return 3.14 * radius_ * radius_; }
private:
    double radius_;
};

Usage:

// 创建不同形状的集合
vector<Shape*> shapes;
shapes.push_back(new Rectangle(2.0, 3.0));
shapes.push_back(new Circle(4.0));

// 使用基类指针计算总面积
double totalArea = 0.0;
for (Shape* shape : shapes) {
    totalArea += shape->area(); // 使用多态性动态绑定函数调用
}

// 输出总面积
cout << "Total area: " << totalArea << endl;

Output:

Total area: 37.68

The above is the detailed content of How to implement polymorphism in C++ class design?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn