The fifth week of learning: the copy compatibility rules of public inheritance

  1. The derived class object can be assigned to the base class object.
    base b; derived d; d=b;
    The member data owned by the derived class object (the base class also has those) is copied over. But the base class cannot assign values ​​to the derived class, because some base classes of the derived class may not have it.
  2. Derived class objects can initialize base class references
    base& b = d
  3. The address of the derived class object can be assigned to the base class pointer
    base* pb = &d . Then pb refers to the public part of the derived class object, so some base classes of the derived class do not have those you can’t use. But the derived class pointer cannot point to the address of the base class object, because you don't have some of the derived class.
Direct base class and indirect base class

A is derived from B, B is derived from C, C is derived from D
A is the direct base class of B, and A is the indirect base class of C

To declare a derived class, just list the direct base class. Derived classes will automatically inherit all indirect base classes along the class hierarchy. So the derived class includes the members defined by itself, all members of the direct base class and the indirect base class.

#include<iostream>
using namespace std;
class son1
{
    
    
	public:
		son1(){
    
    cout<<"Son1 constructor called\n";}
		~son1(){
    
    cout<<"Son1 destructor called\n";}
 } ;
 
 class son2:public son1
 {
    
    
 	public:
 		son2():son1(){
    
    cout<<"Son2 constructor called\n";}
		~son2(){
    
    cout<<"Son2 destructor called\n";}
 };
 
 class son3:public son2
 {
    
    
 	public:
 		son3():son2(){
    
    cout<<"Son3 constructor called\n";}
		~son3(){
    
    cout<<"Son3 destructor called\n";}
 };
 
 int main()
 {
    
    
 	son3 s;
 }

Insert picture description here

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108579898