I want to do essentially the following:
class Base{
void dosomestuff(Derived instanceOfDerived)
{
//Something
}
};
class Derived : public Base{
//Something
};
The Base needs a include of Derived, but to declare Derived it needs the declaration of Base first. Forward declaration does not work, because I do not want to use pointers.
Now my question: How do I accomplish that without pointers? Is that even possible? Or is the only possibility to make instanceOfDerived a pointer?
The original version of the question asks about having Base
hold Derived
as a data member. That's obviously impossible. It's the same infinite recursion problem (a Derived
contains a Base
subobject, so a Base
would recursively contain itself, and it will be turtles all the way down.)
The revised question asks about having a member function of Base
taking a by-value argument of type Derived
. That's perfectly possible. You need a forward declaration of Derived
, and to defer the definition of the member function until after the actual definition of Derived
:
class Derived;
class Base{
void dosomestuff(Derived instanceOfDerived); // declaration only
};
class Derived : public Base{
//Something
};
// out-of-class definition, so making it explicitly inline
// to match the in-class definition semantics
inline void Base::dosomestuff(Derived instanceOfDerived) {
//Something
}
Demo.