views:

249

answers:

5
+1  A: 

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.

Assaf Lavie
+2  A: 

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

serioys sam
+1  A: 

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.

Konrad Rudolph
+1  A: 

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() {}
};
Ferdinand Beyer
You cannot use the `dyanmic_cast` here! The class has no virtual member, hence no runtime type information!
Konrad Rudolph
You are right, I missed that point. Edited my original post -- thanks.
Ferdinand Beyer
N.B. There are a very large number of methods missing in this code, and it's all named very simply to aid understanding. They all have destructors really.
Ed Woodcock
If they all have destructors, than it is really essential to declare them *virtual*, if you haven't already done that!
Ferdinand Beyer
Ahem. IRRELEVANT. This was example code. I'm not asking for tips on my coding style, I know what I'm doing, as a general rule. What I'm asking for is a way of doing what I'm demonstrating above.
Ed Woodcock
You are saying that you need to extract the DDerived specialization from Ptr and pass it to some iterator. If I understand correctly, you will need to up-cast it using dynamic casting, as I described above. Otherwise I still don't get your problem!
Ferdinand Beyer
A: 
Ed Woodcock