Thread: Vectors and subclasses

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    16

    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?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    you should make this function virtual
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Jan 2007
    Posts
    16
    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?
    Last edited by Siphon; 01-06-2007 at 10:11 AM.

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    better yet in all classes, so if you derive from some other class than the component it will still work
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  5. #5
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Should be easy to test, shouldn't it ?
    Kurt

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> 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.

Popular pages Recent additions subscribe to a feed