The implementation mechanism of inheritance and polymorphism in C++: Inheritance: Implemented through inheritance specifiers, derived classes inherit and extend base class behavior. Polymorphism: realized through virtual function table, base class pointer dynamically calls derived class method. Implementation example: Through inheritance and polymorphism, you can create a hierarchy of shape classes and write functions to calculate the total area of any shape.
The implementation mechanism of inheritance and polymorphism in C++
Inheritance and polymorphism are the implementation mechanisms for code reuse and dynamics in C++ Binding is a crucial feature. However, understanding its underlying implementation is important to writing efficient and robust code.
Implementation mechanism
1. Inheritance
Inheritance is a way to create a new class (derived class). This class inherits and extends the behavior of an existing class (base class). In C++, inheritance is implemented through the public
, protected
, or private
inheritance specifiers.
For example:
class Animal { public: virtual void speak() { cout << "Animal sound" << endl; } }; class Dog : public Animal { public: void speak() override { cout << "Woof!" << endl; } };
In this example, the Dog
class inherits the speak()
method of the Animal
base class , and override this method to provide specific behavior.
2. Polymorphism
Polymorphism refers to the ability to dynamically call methods at runtime based on the actual type of the object. It enables base class pointers to access methods in derived class objects.
Polymorphism in C++ is implemented through virtual function tables. During compilation, a vtable entry is generated for each virtual function. When a base class pointer calls a virtual function, it looks up the object's vtable and then calls the appropriate method.
For example:
Animal* animal = new Dog(); animal->speak(); // 输出: "Woof!"
Although animal
points to the Animal
base class, due to polymorphism it will call Dog
The speak()
method in the object.
Practical case
Consider a shape class hierarchy, including the Shape
base class and Circle
, Square
and Triangle
derived classes.
class Shape { public: virtual double area() = 0; }; class Circle : public Shape { public: double area() override { return 3.14 * radius * radius; } }; class Square : public Shape { public: double area() override { return side * side; } }; class Triangle: public Shape { public: double area() override { return 0.5 * base * height; } };
By using inheritance and polymorphism, we can write a calculateTotalArea()
function that can calculate the total area of any shape:
double calculateTotalArea(vector<Shape*>& shapes) { double totalArea = 0; for (Shape* shape : shapes) { totalArea += shape->area(); } return totalArea; }
The above is the detailed content of What is the implementation mechanism of inheritance and polymorphism in C++?. For more information, please follow other related articles on the PHP Chinese website!