Vector inheritance

Discussion in 'Mac Programming' started by ellie:), Feb 27, 2010.

  1. ellie:) macrumors newbie

    Joined:
    Jan 7, 2010
    #1
    I am writing a code , to inherit a vector class like this :

    struct A {

    int dataA;
    int dataB;

    };

    class B : std::vector<A> {

    };


    May I know, how can assign value to the vector, say dataA =5, data B =6 and the second data A =7, data B =9... and how to access the value when I am running the program? Can I call in this way B[0].dataA ?

    thank you..
     
  2. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #2
    Are you sure you want to _inherit_ from std::vector<A> ? It would be a rare case where this is the right thing to do. Ask yourself about class B: _Is_ it a vector, or does it _contain_ a vector? If it _contains_ a vector then you more likely want

    Code:
    class B {
        std::vector<A> data;
        ....
    };
    
    If class B inherits from std::vector<A> then you use exactly the same methods as for vector<A>. If class B contains a vector, then you would for example access myObject.data which is a vector.

    Just realised: Could it be that you don't want to _inherit_ from std::vector at all, that you just want to use a std::vector? You known you can just write

    Code:
    std::vector <A> myVector;
    and myVector will be a vector of struct As. No need for any inheritance at all.
     
  3. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    This sounds like the most likely case. If B was of type std::vector containing a bunch of struct A's, then std::vector's operator [] could be used as the OP described, then the element returned could be .'d to grab a structure element.

    -Lee
     

Share This Page