Archived

This topic is now archived and is closed to further replies.

Deyja

Classes, virtual functions, and a vector.

Recommended Posts

I have a class (Lets call it myclass) with the virtual function void myfunction. I have a class derived from it that overwrites this virtual function. I created an instance of the derived class, casted it to the base class, and pushed it onto a vector of the base class type. When I call ''myfunction'' it''s calling the function on the base class, not the derived class. Do I have to cast it back to the derived type to get the proper function? class myclass { virtual void myfuntion(); }; class derivedclass{ virtual void myfuntion(); }; void myclass::myfunction() { cout << "base class"; } void derivedclass::myfunction() { cout << "derived class"; } void main() { vector vector_of_myclass; derivedclass newinstance; vector_of_myclass.push_back( (myclass)newinstance ); vector_of_myclass[0].myfunction(); } output: "base class". It *should* output ''derived class''. What am I doing wrong?

Share this post


Link to post
Share on other sites
You need to use pointers if you want polymorphism. What you''re experiencing is called slicing, when derived part of the data is thrown away during the cast. Make all your objects dynamic, store pointers in vectors, and you''ll see the expected results.

---
Come to #directxdev IRC channel on AfterNET

Share this post


Link to post
Share on other sites
Thankyou niyaw, it worked buetifully. Though I forgot to clean up after myself the first time I tested(This wasn''t an issue before switching to pointers) and now everything is running terribly slow. :D

My example was ''abstracted''; shall we say. The real situation is much more complex.

Share this post


Link to post
Share on other sites