When instantiating objects from derived classes, how do constructors interact? | Sololearn: Learn to code for FREE!

+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?

4/9/2021 11:37:28 PM

Gustavo Falcão Guimarães

4 Answers

New Answer

+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.

+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🤦🏻‍♂️.

+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

+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.