Is it obligatory to have a default constructor in a superclass to have the possibility to inherit from it? Suppose every derived class constructor is calling one of superclass constructors explicitly, providing the right parameters – will such code work?
Share
No.
If you don’t have default constructor in the base class, you need to call the base class constructor with argument(s) explicitly from the derived class constructor’s member-initialization list.
Example,
Note the syntax of
base("string", 10). It invokes the base class’s constructor, passing"string"as first argument and10as second argument.Also notice
obj(100)which initializes the member variable which is of typeanotherClass:obj(10)invokes the constructor ofanotherClasswhich takesintas argument.