virtual functions

I have a class F where I define a function:
virtual string name(){return "parent"}

I have another class G that extends F and it has a funtion
string name(){ return "child"}

Now in the main I do
vector v;
G g;

and this return "parent" when normally I expect this to return "child"

Can someone please help me.


  • [color=Blue]Usually, the polymorphism is revealed through the POINTERS to objects. That is very important to understand. It means that you need a collection (in your case vector) of POINTERS to base class (F in your case) and then create a POINTER to derived class (G in your case) and include it into collection. Only then the proper virtual method will be invoked. See RED:[/color]
    [color=Red]: typedef F* PTR_TO_F;[/color]
    : vector<[color=Red]PTR_TO_F[/color]> v;
    : G[color=Red]*[/color] g [color=Red]= new G[/color];
    : v.push_back(g);
    : v[0][color=Red]->[/color]name();
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion