Is it always necessary to call base class constructor from derived class constructor? What happens when you don't call it?
What happens if you don't call the base constructor from the derived constructor?
Asked Answered
Guessing C++ from the option and terminology ;-) –
Hyperemia
Assuming you're talking about C++ (anyway, this should be similar in most other languages), if you don't call a constructor of the base class explicitly, its default constructor will be called automatically (if one exists; if not, the compiler would fire an error).
now suppose the base class constructor takes parametrized arguments,bt the derived constructor is empty.in the main function,i declare a derived object without any arguement to the constructor.what will happen?any way to separately pass the base construcotr of that object an arguement? –
Greensboro
No, that's not possible. Your derived class has to pass the arguments to that specific constructor of the base class (if the base class does not provide a default constructor). So, either the constructor of the derived class "knows" the specific values that have to be passed or the derived class asks for those arguments via its constructor as well and just forwards them to the constructor of the base class. –
Len
Nothing at all, since it's absolutely impossible not to do so.
Sure, you can! As I already said: If the base class provides a default constructor, it will be called automatically unless you call a constructor of the base class explicitly. But it's always better to call the constructor explicitly just to indicate what's the purpose. –
Len
@Len - not sure why you said you can, you just explained why you can't. –
Selfdenial
© 2022 - 2024 — McMap. All rights reserved.