C++ Advanced (7)-Inheritance and Derivation 6

Derived class copy constructor

The case where the derived class does not define a copy constructor

  • The compiler will generate an implicit copy constructor when needed;
  • First call the copy constructor of the base class;
  • Then perform replication for the newly added members of the derived class.

The case where the derived class defines the copy constructor

  • It is generally necessary to pass parameters to the copy constructor of the base class.
  • The copy constructor can only accept one parameter, which is used to initialize the members defined by the derived class and will also be passed to the copy constructor of the base class.
  • The parameter type of the copy constructor of the base class is the reference of the base class object, and the actual parameter can be the reference of the derived class object
  • For example: C::C(const C &c1): B(c1) {...}

Destructor of derived class

  • The destructor is not inherited, and the derived class must declare its own destructor if necessary.
  • The declaration method is the same as the destructor of the class without inheritance.
  • No need to explicitly call the destructor of the base class, the system will automatically call it implicitly.
  • The body of the destructor of the derived class is executed first, and then the destructor of the base class is called.

Examples of Destruction of Derived Objects

#include <iostream>
using namespace std;
class Base1 {   
public:
    Base1(int i) 
   { cout << "Constructing Base1 " << i << endl; }
    ~Base1() { cout << "Destructing Base1" << endl; }
};
class Base2 {
public:
    Base2(int j) 
   { cout << "Constructing Base2 " << j << endl; }
    ~Base2() { cout << "Destructing Base2" << endl; }
};
class Base3 {
public:
    Base3() { cout << "Constructing Base3 *" << endl; }
    ~Base3() { cout << "Destructing Base3" << endl; }
};

class Derived: public Base2, public Base1, public Base3 {
public: 
    Derived(int a, int b, int c, int d): Base1(a), member2(d), member1(c), Base2(b)
  { }   
private:    
    Base1 member1;
    Base2 member2;
    Base3 member3;
};

int main() {
    Derived obj(1, 2, 3, 4);
    return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_41023026/article/details/108569085