+ 2

When instantiating objects from derived classes, how do constructors interact?

If we instantiate an object whose class derives from another class, both with their own constructors, what happens? Do both constructors get looped through? In which order?

9th Apr 2021, 11:37 PM
Gustavo Falcão Guimarães
Gustavo Falcão Guimarães - avatar
4 odpowiedzi
+ 3
You can figure this out on your own by writing a simple program with parent and child classes. Create a constructor in each and add an output statement in each constructor to identify which constructor it is. Then run it and see the results.
9th Apr 2021, 11:47 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
I'm on mobile, and coding on it is really bad because of autocorect. Anyways, I tried that just after posting, and if I'm not mistaken, constructors seem to be 'uninheritable'. Objects instantiated from derived classes don't seem to 'trigger' the base class's constructors, just their own. Is that the case? Edit: nevermind, they do. Autocorect screwed my code by accidentally commenting base class constructor's only statement🤦🏻‍♂️.
9th Apr 2021, 11:57 PM
Gustavo Falcão Guimarães
Gustavo Falcão Guimarães - avatar
+ 1
Here you can see how simply creating a instance of the Child class that the Parent classes constructor is called then the child class constructor. Then when the object is destroyed (goes out of scope in this case) the Child class destructor is called then the parents. The parent class basically wraps the class. https://code.sololearn.com/cfBG1sSzmH3j/?ref=app
10th Apr 2021, 12:22 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
From what I can see the constructor from the inheritade class called before and then the delivered class after the destructor from the delivered class is called and then the one from inheritade class.
16th Apr 2021, 7:00 AM
Nshuti Alliance
Nshuti Alliance - avatar