I have the following class hierarchy with a virtual GrandParent and non-virtual Parent and Child:
class GrandParent {
protected:
explicit GrandParent(const float &max_dur);
virtual ~GrandParent() {}
private:
const float _max_dur;
};
class Parent : public virtual GrandParent {
public:
explicit Parent(const float &max_dur = 0);
};
class Child : public Parent {
public:
explicit Child(const float &max_dur = 0);
};
Their constructors are nested like so:
// GrandParent constructor
GrandParent::GrandParent(const float &max_dur)
: _max_dur{max_dur} {}
// Use GrandParent constructor
Parent::Parent(const float &max_dur)
: GrandParent{max_dur} {}
// Use Parent constructor
Child::Child(const float &max_dur)
: Parent{max_dur} {} // <- error occurs here
When I build, I get the following error message:
error: no matching function for call to ‘GrandParent::GrandParent()’
It seems as if the Child constructor is ignored and it jumps to GrandParent instead. Modifying the Child constructor to directly call the GrandParent constructor (thus skipping a generation), I can bypass the error but it seems like the wrong approach.
Thanks in advance for your help!
Solution
Fixed by following 463035818-is-not-a-number's answer to call the GrandParent's constructor explicitly and 康桓瑋's suggestion in order to call the Parent's constructor as well:
Child::Child(const float &max_dur)
: GrandParent{max_dur}, Parent{max_dur} {}