Vectors and subclasses

This is a discussion on Vectors and subclasses within the C++ Programming forums, part of the General Programming Boards category; I have a vector that looks like this: Code: vector<component*> v; That contains all kinds of different objects (arms, legs, ...

  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
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    you should make this function virtual
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  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 09:11 AM.

  4. #4
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    better yet in all classes, so if you derive from some other class than the component it will still work
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  5. #5
    ZuK
    ZuK is offline
    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,327
    >> 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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21