Home >Backend Development >C++ >C++ Virtual Functions and Virtual Inheritance: Uncovering the Complexities of Multiple Inheritance
Virtual function: allows derived classes to override functions in base classes. When the base class pointer points to a derived class object, the virtual function of the derived class is called. Virtual inheritance: Solve the diamond inheritance problem in multiple inheritance. Ensure that only one instance of each base class exists in the derived class.
Virtual functions are a type of C A special type of member function that allows a derived class to override functions in a base class. When a base class pointer or reference points to a derived class object, the virtual function of the derived class will be called.
class Shape { public: virtual double area() const = 0; // 纯虚函数 }; class Rectangle : public Shape { public: Rectangle(double width, double height) : m_width(width), m_height(height) {} double area() const override { return m_width * m_height; } // 重写虚函数 private: double m_width; double m_height; };
Virtual inheritance is a technique used to solve the diamond inheritance problem that occurs in multiple inheritance (also known as the ambiguity of multiple inheritance).
class Animal { public: virtual void speak() const { cout << "Animal speaks" << endl; } }; class Dog : virtual public Animal { // 虚继承 public: void speak() const override { cout << "Dog barks" << endl; } }; class Cat : virtual public Animal { // 虚继承 public: void speak() const override { cout << "Cat meows" << endl; } }; class SiberianHusky : public Dog, public Cat { // 多重继承 public: void speak() const override { cout << "Siberian Husky howls" << endl; } };
Virtual inheritance ensures that each base class (Animal
) has only one instance in the derived class (SiberianHusky
), thus avoiding the diamond inheritance problem.
#include <iostream> using namespace std; class Shape { public: virtual double area() const = 0; }; class Rectangle : public Shape { public: Rectangle(double width, double height) : m_width(width), m_height(height) {} double area() const override { return m_width * m_height; } private: double m_width; double m_height; }; class Circle : public Shape { public: Circle(double radius) : m_radius(radius) {} double area() const override { return M_PI * m_radius * m_radius; } private: double m_radius; }; int main() { // 创建形状的父类指针 Shape* shape; // 创建矩形对象并将其分配给父类指针 shape = new Rectangle(5, 10); cout << "矩形面积:" << shape->area() << endl; // 创建圆形对象并将其分配给父类指针 shape = new Circle(3); cout << "圆形面积:" << shape->area() << endl; return 0; }
The above is the detailed content of C++ Virtual Functions and Virtual Inheritance: Uncovering the Complexities of Multiple Inheritance. For more information, please follow other related articles on the PHP Chinese website!