Error : base class constructor must explicitly initialize parent class constructor
The parent class has an explicit constructor, so compiler will not add an implicit 'empty' constructor to it. Additionally your constructor has a parameter, so compiler can not generate an implicit call to it. That's why you must do it explicitly.
This way:
child::child(int a) : parent(a)
{
}
When you initialize an object of a derived class, the base class part has to be constructed first. If you don't initialize it yourself in the derived class' constructor by calling one of its constructors, the compiler will attempt use the default constructor of the base class. In your case the default constructor is not defined because you already provided a custom constructor.
To solve this you will either have to provide a default constructor for the base class or simply call its constructor in the derived class' constructor's initializer list:
child::child(int a) : parent(a)
{
}
At the risk of repeating the error message you got: a child class constructor must invoke its parent's constructor.
The compiler will add an automatic invocation of the parent's default (argumentless) constructor. If the parent does not have a default constructor, you must explicitly invoke one of the constructors it does have by yourself.
The compiler has to enforce this to ensure that the functionality that the child class has inherited from the parent is set up correctly... for example, initialising any private variables that the child has inherited from the parent, but cannot access directly. Even though your class doesn't have this problem, you must still follow the rules.
Here are some examples of constructors in classes using inheritance:
This is fine, ParentA has a default constructor:
class ParentA
{
};
class ChildA
{
public:
ChildA() {}
};
This is not fine; ParentB has no default constructor, so ChildB1 class must explicitly call one of the constructors itself:
class ParentB
{
int m_a;
public:
ParentB(int a) : m_a(a) {}
};
class ChildB1 : public ParentB
{
float m_b;
public:
// You'll get an error like this here:
// "error: no matching function for call to ‘ParentB::ParentB()’"
ChildB1 (float b) : m_b(b) {}
};
This is fine, we're calling ParentB's constructor explicitly:
class ChildB2 : public ParentB
{
float m_b;
public:
ChildB2(int a, float b) : ParentB(a), m_b(b) {}
};
This is fine, ParentC has a default constructor that will be called automatically:
class ParentC
{
int m_a;
public:
ParentC() : m_a(0) {}
ParentC(int a) : m_a(a) {}
};
class ChildC: public ParentC
{
float m_b;
public:
ChildC(float b) : m_b(b) {}
};