Home > Backend Development > C++ > How are Constructors and Destructors Called in C Inheritance?

How are Constructors and Destructors Called in C Inheritance?

Patricia Arquette
Release: 2024-11-29 04:10:09
Original
296 people have browsed it

How are Constructors and Destructors Called in C   Inheritance?

Order of Constructor and Destructor Calls in Inheritance

In object-oriented programming with inheritance, understanding the order of constructor and destructor calls is crucial. This becomes particularly important when dealing with multiple base classes and object compositions.

Consider the following class hierarchy:

struct A {
    A() { cout << "A() C-tor" << endl; }
    ~A() { cout << "~A() D-tor" << endl; }
};

struct B : public A {
    B() { cout << "B() C-tor" << endl; }
    ~B() { cout << "~B() D-tor" << endl; }

    A a;
};
Copy after login

In the main function:

int main() {
    B b;
}
Copy after login

Here are the rules governing the order of constructor and destructor calls in this inheritance hierarchy:

Constructor Calls:

  1. Base Class Construction: Constructor calls begin with the base class. In this case, A's constructor is called first.
  2. Member Field Construction: Next, member fields are constructed in the order they are declared in the derived class. In this case, B's field a of type A is constructed.
  3. Derived Class Construction: Finally, the constructor of the derived class, B, is called.

Destructor Calls:

The order of destructor calls is the reverse of the constructor call order:

  1. Derived Class Destructor: The destructor of the derived class, B, is called first.
  2. Member Field Destructor: Next, the destructor of the member field a is called, destroying its instance of A.
  3. Base Class Destructor: Finally, the destructor of the base class, A, is called.

Default Initialization List:

Even without an explicitly defined initialization list, the member field will be initialized before the derived class constructor is called. In this case, a would be initialized to the default constructor of A.

Therefore, the expected output for the code in the main function would be:

A() C-tor
A() C-tor
B() C-tor
~B() D-tor
~A() D-tor
~A() D-tor
Copy after login

The above is the detailed content of How are Constructors and Destructors Called in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template