lundi 20 avril 2015

C++ covariant returning type application

I wanted to ask about covariant return type and a possible (not) application. I thought I had discovered some new design pattern, but sadly it does not work :(

Let's start with an example:

// test.h 
class B {public: virtual B* getSelf() {return this;} };
class D : public B { public: D* getSelf() {return static_cast<D*>(this);} };

void compute(B* something); 
void compute(D* something);

// test.cpp 
int main() 
{
B* b = new D(); 
compute(b->getSelf()); // This calls compute(B*), not compute(D*) 
}

Any idea of why it does not work?

PS I apologize for the poor formatation

Edit: Of course, it correctly calls compute(D*) if I use a cast in the main.

Edit #2: I'm trying to avoid switch as much as I can :)

Aucun commentaire:

Enregistrer un commentaire