C++ Inheritance

In object-oriented programming, one of the most important concepts is inheritance. Inheritance allows us to define a class based on another class, which makes creating and maintaining an application easier. In doing so, it also achieves the effect of reusing code functionality and improving execution efficiency.

When creating a class, you do not need to rewrite new data members and member functions; you only need to specify that the newly created class inherits the members of an existing class. This existing class is calledbase class, the newly created class is calledderived class。

Inheritance representsis arelationship. For example, mammals are animals, dogs are mammals, therefore, dogs are animals, and so on.

The code is as follows:

// Base class
class Animal {
    // eat() function
    // sleep() function
};


// derived class
class Dog : public Animal {
    // bark() function
};

Base class & Derived class

A class can be derived from multiple classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base classes. The class derivation list names one or more base classes, in the following form:

class derived-class: access-specifier base-class

Here, the access modifier access-specifier ispublic、protectedorprivateAmong them, base-class is the name of a class previously defined. If no access modifier access-specifier is used, it defaults to private.

Suppose there is a base classShape,Rectangleis its derived class, as shown below:

Example

#include <iostream> using namespace std; // Base class class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Derived class class Rectangle: public Shape { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; Rect.setWidth(5); Rect.setHeight(7); // Output the area of the object cout << "Total area: " << Rect.getArea() << endl; return 0; }

When the above code is compiled and executed, it produces the following results:

Total area: 35

Access control and inheritance

A derived class can access all non-private members of the base class. Therefore, if a base class member is not intended to be accessed by member functions of the derived class, it should be declared private in the base class.

We can summarize the different access types according to access permissions, as follows:

Visitpublicprotectedprivate
the same classyesyesyes
derived classyesyesno
external classesyesnono

A derived class inherits all base class methods, except for the following cases:

  • The base class's constructor, destructor, and copy constructor.
  • Overloaded operators of the base class.
  • Friend functions of the base class.

Inheritance Types

When a class is derived from a base class, the base class can be inherited aspublic、protectedor privateseveral types. The inheritance type is specified by the access modifier access-specifier explained above.

We rarely useprotectedor privateinheritance, usually usingpublicInheritance. When using different types of inheritance, follow the following rules:

  • Public inheritance (public):When a class is derived frompublica base class, the base class'spublicMembers also belong to the derived class.publicmembers, the base class'sprotectedMembers also belong to the derived class.protectedmembers, the base class'sprivateMembers cannot be directly accessed by the derived class, but they can be accessed by calling the base class'spublicandprotectedmembers to access.
  • Protected inheritance (protected):When a class is derived fromprotecteda base class, the base class'spublicandprotectedMembers will become members of the derived class.protectedmembers.
  • Private inheritance (private):When a class is derived fromprivatea base class, the base class'spublicandprotectedMembers will become members of the derived class.privatemembers.

Multiple inheritance

Multiple inheritance means that a subclass can have multiple parent classes, and it inherits the characteristics of multiple parent classes.

C++ classes can inherit members from multiple classes, with the syntax as follows:

class <派生类名>:<继承方式1><基类名1>,<继承方式2><基类名2>,…
{
<派生类类体>
};

where the access modifier inheritance method ispublic、protectedorprivateOne of them is used to modify each base class, and the base classes are separated by commas, as shown above. Now let's look at the following example together:

Example

#include <iostream> using namespace std; // Base class Shape class Shape { public: void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: int width; int height; }; // Base class PaintCost class PaintCost { public: int getCost(int area) { return area * 70; } }; // Derived class class Rectangle: public Shape, public PaintCost { public: int getArea() { return (width * height); } }; int main(void) { Rectangle Rect; int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // Output the area of the object cout << "Total area: " << Rect.getArea() << endl; // Output total cost cout << "Total paint cost: $" << Rect.getCost(area) << endl; return 0; }

When the above code is compiled and executed, it produces the following results:

Total area: 35
Total paint cost: $2450
other extensions