I have a class Grandparent which is provided by a library. I’d like to define an interface for subclasses of Grandparent, so I created an abstract subclass called Parent:
class Grandparent {
public:
Grandparent(const char*, const char*);
};
class Parent : public Grandparent {
public:
virtual int DoSomething() = 0;
};
The constructor for Grandparent takes two arguments. I’d like my child class, Child, to also have a constructor with two arguments, and just pass these to the constructor for Grandparent… something like
class Child : public Parent {
public:
Child(const char *string1, const char *string2)
: Grandparent(string1, string2)
{}
virtual int DoSomething() { return 5; }
};
Of course, Child’s constructor can’t call its grandparent class’s constructor, only its parent class’s constructor. But since Parent can’t have a constructor, how can I pass these values to the grandparent’s constructor?
Parentcan certainly have a constructor. It must, if it’s going to call theGrandparentconstructor with any parameters.There’s nothing forbidding abstract classes from having constructors, destructors, or any other kind of member function. It can even have member variables.
Simply add the constructor to
Parent. InChild, you’ll call theParentconstructor; you can’t “skip a generation” with constructor calls.