I am starting to use virtual functions, and i am programming a simple text game, my question is this, if i have a virtual function called spec_abil with in a Super class called rpg_class. If you allow the player to class what class they want to play, say a mage class, a archer class, and a warrior class, which all have their own spec_abil function. How do you write it so that the program knows which one to use depending on the chosen class.
|
closed as off topic by Tetrad♦ Mar 25 '12 at 17:16
Questions on Game Development Stack Exchange are expected to relate to game development within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.
|
Declaring a method as virtual in a base class causes the compiler to introduce a hidden pointer into objects of this class (and its derived classes). This is the You must be aware of how virtual methods work in order to use them safely. I recommend further reading, inclusing virtual destructors (very important). Polymorphism can be exploited with or without pointers, using dynamically allocated objects or automatically cleaned up objects. References can be used instead of pointers:
Produces this output:
Caveat for beginners: beware the subtle differences in the use of pointers and references. Best to learn pointers exclusively first I would think. |
|||||||
|
|
It's automatic as long as you're calling the virtual method through a pointer or reference to your base class - that's the beauty of polymorphism! So to give a typical example using pointers, imagine you had these three classes:
The following example would automatically work:
And it works because the vector is storing pointers to the base class (i.e. PS: You might also want to consider using a smart pointer such as |
|||||||||
|