The Child constructor in the code below calls its parent constructor to initialise itself. However the code won't compile unless Child also calls the Grandparent constructor, even though this is an implementation detail that's supposed to be hidden within Parent. I don't want to expose this detail to users of the Child class, as it may change in future. How can I get the code below working?
I tried changing the inheritance to 'private', but the Child constructor was still expected to know about this private arrangement, which IMHO somewhat defeats the purpose of private inheritance!
Any suggestions?
#include <iostream>
class MyObject {
public:
MyObject(int i) {
std::cout << "MyObject(" << i << ") constructor" << std::endl;
}
};
class Grandparent {
public:
Grandparent(MyObject i)
{
};
};
class Parent: virtual public Grandparent {
public:
Parent(int j) :
Grandparent(MyObject(j))
{
};
};
class Child: virtual public Parent {
public:
Child() :
//Grandparent(MyObject(123)), // Won't work without this
Parent(5)
{
};
};
int main(void)
{
Child c;
return 0;
}
$ g++ -o test test.cpp test.cpp: In constructor ‘Child::Child()’: test.cpp:29: error: no matching function for call to ‘Grandparent::Grandparent()’ test.cpp:12: note: candidates are: Grandparent::Grandparent(MyObject) test.cpp:10: note: Grandparent::Grandparent(const Grandparent&)