That makes sense. Base doesn't have such a method (DerivedMethod). If DerivedMethod were a virtual function (could be pure
) of the base class it'd work.
This code doesn't work because template class Ptr returns the object of Class of Base Template not Class of Derived Template. Derived Method is part of derived template so this throws compilation error. Whereas if DerivedMethod was part of Base Template this code will work
The compiler is right. In order for you to be able to access a method, this method must be declared in the type that the compiler sees (this is called the static type of a variable). In your case, this type is Base<…>
and the compiler has no clue that it's something else.
It is really hard to figure out what you actually want to achieve, using your abstract class and member names. If you really have to treat the pointer within Ptr
as a D_Derived
, add an accessor member to Ptr
and use type casting:
class Ptr {
...
Base<f,g,Ptr<f,g> >* get() {
return in;
}
};
...
D_Derived* ptr = dynamic_cast<D_Derived*>(p.get());
if (ptr) {
ptr->DerivedMethod();
}
EDIT: As Konrad Rudolph pointed out, in order to use dynamic casting, you will have to add a virtual method to your base class.
Actually it is a good practice to define a virtual destructor for every class that you want to use as a base class anyway, to ensure the destructor of your derived class will be called (More Information).
class RealBase {
public:
virtual ~RealBase() {}
};