Is it always necessary to call base class constructor from derived class constructor? What happens when you don't call it?
The appropriate Derived constructor is called. The Base object is constructed first using the appropriate Base constructor. If no base constructor is specified, the default constructor will be used. The member initializer list initializes variables.
If no constructors are explicitly declared in the class, a default constructor is provided automatically by the compiler.
Whenever the derived class's default constructor is called, the base class's default constructor is called automatically. To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly.
In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class.
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).
If 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