-
Vectors and subclasses
I have a vector that looks like this:
Code:
vector<component*> v;
That contains all kinds of different objects (arms, legs, battery etc) that inherit component, such as:
Code:
class arms: public component { ... }
And my problem is.. After I put them into the component-vector, every time I try to call their print_info() function, I get the components print_info()-function, and that one is missing stuff that I want to get printed out to the screen.
Is there any way to call the RIGHT print_info()-function after putting the arms, legs and battery objects into the component*-vector?
-
you should make this function virtual
-
All I have to do is change the declaration of print_info in component.h to "virtual void" instead of "void" and the problem is solved?
-
better yet in all classes, so if you derive from some other class than the component it will still work
-
Should be easy to test, shouldn't it ?
Kurt
-
>> All I have to do is change the declaration of print_info in component.h to "virtual void" instead of "void" and the problem is solved?
Assuming you are doing everything else correctly. There are other potential reasons that could be happening, but a missing virtual is the most obvious possibility.
>> better yet in all classes, so if you derive from some other class than the component it will still work
If the function is virtual in the base class, it will be virtual in all derived classes, even those further down the line.