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?
is it obligatory to have a default constructor in a superclass to have the possibility to inherit from it?
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,
class base
{
public:
base(std::string const & s, int n);
};
class derived : public base
{
anotherClass obj;
public:
derived() : base("string", 10), obj(100)
{ //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ member-initialization list
}
};
Note the syntax of base("string", 10)
. It invokes the base class's constructor, passing "string"
as first argument and 10
as second argument.
Also notice obj(100)
which initializes the member variable which is of type anotherClass
: obj(10)
invokes the constructor of anotherClass
which takes int
as argument.