I plan to create an interface (rather a virtual base class in c++) with a method that takes an argument of the own type.
class Base {
public:
virtual voi
You can't do this directly. Think about this case:
Base b;
Derived d;
Base& d_ref = d;
d_ref.seriousMethod(b); // What happens here?
At compile-time, the variable d_ref
has static type Base
, so according to the definition of Base
, it should be able to take b
as a parameter to seriousMethod
.
But at runtime, the dynamic type of d_ref
is Derived
, so it according to the definition of Derived
, it can't take b
as a parameter to seriousMethod
. It can't convert b
to Dervied
since it might be a straight Base
object (if Base
is not abstract), or it might be some other class derived from Base
that is not the same as Derived
.
You are correct in assuming that the only real way to go about this is the curiously-recurring template pattern, i.e. templating Base
and defining Dervied
as:
class Derived : public Base { ... }
This removes the problem illustrated above, because each type derived from Base
will have a distinct base class, and will not be related to one another through inheritance.