# # # c + + inheritance

One of the most important concepts in object-oriented programming is inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. In doing so, you also achieve the effect of reusing code functionality and improving execution time. When creating a class, you don’t need to rewrite new data members and member functions. You can just specify that the new class inherits members of an existing class. This existing class is called a base class, and the new class is called a derived class. Inheritance represents is A relationship. For example, mammals are animals, dogs are mammals, therefore, dogs are animals, and so on. #### Base & Derived Classes A class can be derived from more than one class, which means it can inherit data and functions from more than one base class. To define a derived class, we use a list of class derivations to specify the base class. Class derived lists are named after one or more base classes and have the following form:

class derived-class: access-specifier base-class
Copy the code

The access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, the default is private.

###### The following is an example:

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

	system("pause"); } Output: Total area: 35Copy the code

#### Access control and inheritance Derived classes can access all non-private members of the base class. So base class members that do not want to be accessed by member functions of derived classes should be declared private in the base class. We can summarize the different types of access based on access permissions, as follows:

access public protected private
The same class yes yes yes
Derived classes yes yes no
Outside of the class yes no no

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

  • The base class constructor, destructor, and copy constructor.
  • An overloaded operator for the base class.
  • Friend functions of the base class. #### Inherited Type When a class is derived from a base class, the base class can be inherited as public, protected, or private. The inheritance type is specified by the access-specifier described above. We rarely use protected or private inheritance, usually public. When using different types of inheritance, follow these rules:
  • Public inheritance: When a class is derived from a public base class, the public members of the base class are also the public members of the derived class. The protected members of the base class are also the protected members of the derived class. The private members of the base class cannot be accessed directly by the derived class, but can be accessed by calling the public and protected members of the base class.
  • Protected inheritance: When a class is derived from a protected base, the public and protected members of the base become protected members of the derived class.
  • Private Inheritance (private) : When a derived class has a base class, the public and protected members of the base class become private members of the derived class. #### multiple inheritance Multiple inheritance means that a subclass can have more than one parent class, which inherits the features of multiple parent classes. C++ classes can inherit members from multiple classes using the following syntax:
Class < derived class name >:< inheritance 1>< base class name 1>,< inheritance 2>< base class name 2>,... {< derived class body >};Copy the code

The access modifier inheritance is either public, protected, or private, and is used to modify each base class, separated by commas, as shown above.

###### The following is an example:

#include <iostream>using namespace std; Shape class Shape {public: voidsetWidth(int w)
	{
		width = w;
	}
	void setHeight(int h) { height = h; } protected: int width; int height; }; PaintCost class PaintCost {public: int getCost(int area) {returnarea * 70; }}; Class Rectangle: public Shape, public PaintCost {public: intgetArea()
	{
		return(width * height); }}; int main(void) { Rectangle Rect; int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // The area of the output object cout <<"Total area: "<< Rect.getArea() << endl; // Output total cost cout <<"Total paint cost: $" << Rect.getCost(area) << endl;
	system("pause");
	return0; } Output: Total area: 35 Total paint cost:The $2450
Copy the code

####C++ polymorphism polymorphism literally means multiple forms. Polymorphism is used when there is a hierarchy between classes and the classes are related by inheritance. C++ polymorphism means that when a member function is called, different functions are executed depending on the type of object on which the function is called. ###### The following is an error example:

#include <iostream> 
using namespace std;

class Shape {
protected:
	int width, height;
public:
	Shape(int a = 0, int b = 0)
	{
		width = a;
		height = b;
	}
	int area()
	{
		cout << "Parent class" << endl;
		return0; }}; class Rectangle : public Shape { public: Rectangle(int a = 0, int b = 0) :Shape(a, b) { } intarea()
	{
		cout << "Rectangle class" << endl;
		return(width * height); }}; class Triangle : public Shape { public: Triangle(int a = 0, int b = 0) :Shape(a, b) { } intarea()
	{
		cout << "Triangle class" << endl;
		return(width * height / 2); }}; Void getArea(Shape& p) {cout <<"area : "<< p.area() << endl; } // The program's main function intmain()
{
	Rectangle rec(10, 10);
	Triangle  tri(10, 10);

	getArea(rec);
	getArea(tri);
	system("pause");
	return0; } Parent class area: 0 Parent class area: 0Copy the code

The reason for the error output is that the calling function area() is set by the compiler to a version in the base class, which is known as static polymorphism, or static linking – function calls are prepared before the program executes. This is sometimes referred to as early binding, because the area() function is set up during program compilation. But for now, let’s change the program a little bit and place the keyword virtual before the declaration of area() in Shape. ######class Shape is modified as follows (set the keyword virtual) :

class Shape {
protected:
	int width, height;
public:
	Shape(int a = 0, int b = 0)
	{
		width = a;
		height = b;
	}
	int virtual area()
	{
		cout << "Parent class" << endl;
		return0; }}; Rectangle class area: 100 Triangle class area: 50Copy the code

At this point, the compiler looks at the contents of the pointer, not its type. Therefore, since the addresses of tri and REc class objects are stored in * Shape, their respective area() functions are called. As you can see, each subclass has a separate implementation of the function area(). That’s how polymorphism is used in general. With polymorphism, you can have multiple different classes, functions with the same name but different implementations, and functions with even the same parameters. # # # # virtual functions

Virtual functions are functions declared in the base class using the keyword virtual. When a virtual function defined in the base class is redefined in a derived class, the compiler is told not to statically link to the function. What we want is for any point in the program to be able to choose which function to call based on the type of object being called. This operation is called dynamic linking, or late binding. Pure virtual functions are used when you might want to define a virtual function in a base class so that it can be redefined in a derived class to better fit objects, but you can’t give a meaningful implementation of the virtual function in the base class. We can rewrite the area() function in the base class as follows:

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      // pure virtual function
      virtual int area() = 0;
};
Copy the code

######= 0 tells the compiler that the function has no body and that the above virtual function is pure virtual. # # # # # note:

Void funtion1()=0; Pure virtual functions must not be defined. Pure virtual functions are used to regulate the behavior of derived classes, called interfaces. Classes that contain pure virtual functions are abstract classes that cannot define instances, but can declare Pointers or references to concrete classes that implement the abstract class. Virtual ReturnType FunctionName(Parameter) the virtual function must be implemented. If it is not implemented, the compiler will error: error LNK****: unresolved external symbol “public: Virtual void __thiscall ClassName: : virtualFunctionName (void) “3, for virtual function, parent and child classes have their own versions. Dynamically bound when called by polymorphic mode. 4, the implementation of a pure virtual function subclass, the pure virtual function programming in the subclass of the virtual function, the subclass of the subclass that is, the sun tzu class can cover the virtual function, called by the polymorphic dynamic binding. Virtual functions are the mechanism used in C++ to achieve polymorphism. The core idea is to access functions defined by derived classes through base classes. The destructor must be virtual, but not necessarily pure virtual, when there is dynamic allocation of memory on the heap. Friends are not member functions. Only member functions can be virtual, so friends cannot be virtual functions. But you can solve the friend virtuality problem by having a friend function call a virtual member function. The destructor should be virtual and will call the destructor of the corresponding object type. Therefore, if the pointer points to a subclass object, the subclass’s destructor will be called and the base class’s destructor will be automatically called.

##### Conclusion: there are three conditions for the formation of polymorphism in ###### :

  • There must be an inheritance relationship
  • Inheritance relationships must have virtual functions of the same name
  • There is a pointer or reference to the base class type through which the virtual function is called.

####C++ interface (abstract class)

Interfaces describe the behavior and functionality of a class without completing a specific implementation of the class. C++ interfaces are implemented using abstract classes, which are not confused with data abstraction, a concept that separates implementation details from related data. Abstract classes, often called ABCs, are designed to provide an appropriate base class from which other classes can inherit. An abstract class cannot be used to instantiate an object; it can only be used as an interface. Attempting to instantiate an object of an abstract class results in a compilation error. Therefore, if an ABC subclass needs to be instantiated, each virtual function must be implemented, which also means that C++ supports using ABC to declare interfaces. Attempting to instantiate an object of a derived class without overloading a pure virtual function results in a compilation error. Classes that can be used to instantiate objects are called concrete classes. ###### The following is an example:

#include <iostream>using namespace std; Class Shape {public: int getArea() = 0; voidsetWidth(int w)
	{
		width = w;
	}
	void setHeight(int h) { height = h; } protected: int width; int height; }; Class Rectangle: public Shape {public: intgetArea()
	{
		return(width * height); }}; class Triangle : public Shape { public: intgetArea()
	{
		return(width * height) / 2; }}; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // The area of the output object cout <<"Total Rectangle area: "<< Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // The area of the output object cout <<"Total Triangle area: " << Tri.getArea() << endl;
	system("pause");
	return0; } Rectangle area: 35 Total Triangle area: 17Copy the code

##### abstract class for inheritance constraints

An object-oriented system might use an abstract base class to provide a proper, generic, standardized interface for all external applications. The derived class then inherits all similar operations by inheriting the abstract base class. Functions provided by external applications (that is, public functions) exist as pure virtual functions in abstract base classes. These pure virtual functions are implemented in the corresponding derived classes. This architecture also makes it easy for new applications to be added to the system, even after the system has been defined.

Special thanks: rookie C++ tutorial