A little question about creating objects. Say I have these two classes:
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; };
and in main I create an instance of B
:
int main(){ B b; }
Note that B
derives from A
and also has a field of type A
.
I am trying to figure out the rules. I know that when constructing an object first calls its parent constructor, and vice versa when destructing.
What about fields (A a;
in this case)? When B
is created, when will it call A
's constructor? I haven't defined an initialization list, is there some kind of a default list? And if there's no default list? And the same question about destructing.
For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.
Answer: the order of execution of constructor and destructor call in c# inheritance: The constructor call is from top to bottom i.e. from base class to the derive class. And the destructor call is in reverse order i.e. from bottom to the top.
Destructors for virtual base classes are called in the reverse order of declaration.
Class E (member object 1) destructor is called and finishes. Class C (base of F) destructor is called and finishes.
class
. If there are multiple base class
es then, construction starts with the left most base. (side note: If there is a virtual
inheritance then it's given higher preference).class
itself is constructedIrrespective of the initializer list, the call order will be like this:
class A
's constructorclass B
's field named a
(of type class A
) will be constructedclass B
's constructorIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With