Home > Article > Backend Development > How is inheritance used to build class hierarchies in C++?
C++ Inheritance is used to build class hierarchies, where new classes (derived classes) inherit functionality from a base class and extend its functionality. Derived classes use access specifiers to declare inheritance relationships and control access to base class members. public grants access to derived classes and external code, protected grants access to derived classes and their derived classes, and private grants access to derived classes only. By creating a derived class and overriding the pure virtual function of the base class, the derived class can implement custom functions, such as the implementation of Rectangle and Circle in the example to calculate the area of a specific shape.
Inheritance is a basic concept in object-oriented programming. Allows creation of new classes from existing classes. In C++, inheritance can be used to build a class hierarchy where each class inherits from its base class and possibly extends its functionality.
In order to inherit from a base class, the new class (derived class) must use public
, protected
or private
Access specifier declares inheritance relationship. The syntax is as follows:
class 派生类 : 访问说明符 基类 { // 派生类成员 };
##Access specifier Controls the access rights of derived classes to base class members:
: Allow derived classes and external code to access base class members.
: Allow derived classes and their derived classes to access base class members.
: Only derived classes are allowed to access base class members.
class Shape { public: virtual double getArea() const = 0; // 纯虚函数 }; class Rectangle : public Shape { public: Rectangle(double width, double height) : _width(width), _height(height) {} double getArea() const override { return _width * _height; } private: double _width, _height; }; class Circle : public Shape { public: Circle(double radius) : _radius(radius) {} double getArea() const override { return 3.14159 * _radius * _radius; } private: double _radius; };ExampleIn this example ,
Shape is the base class of the shape class, which contains a pure virtual function
getArea(), which means it must be implemented in all derived classes.
is a rectangle class that inherits from
Shape and overrides the
getArea() function to calculate the area of a rectangle.
is another circle class inherited from
Shape, which also overrides the
getArea() function to calculate the area of a circle.
Rectangle and
Circle objects and call the
getArea() function:
int main() { Rectangle rectangle(2.0, 3.0); cout << "Rectangle area: " << rectangle.getArea() << endl; Circle circle(5.0); cout << "Circle area: " << circle.getArea() << endl; return 0; }Output:
Rectangle area: 6 Circle area: 78.5398163397
The above is the detailed content of How is inheritance used to build class hierarchies in C++?. For more information, please follow other related articles on the PHP Chinese website!