Vector inheritance question

Jun 9, 2009 at 4:05pm
I was just wondering if this would work:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class a
{
    int a;
};

class b public a
{
    int b;
};

int main()
{
   vector<a> listOfStuff;
   listOfStuff.push_back( b )

}


Just made that up... but what I actually want to do is a have a big list of Items, using class Item{}; & vector<Item> itemList; and have items within itemList that are from of type class Itemtype public Item{};. Is this allowed?

ps. sorry that was badly written, but i *think* it's clear enough.
Jun 9, 2009 at 4:44pm
There are a few mistakes in the code you posted. Anyway, that would work as 'b' can be easily casted to 'a' but you will loose the extra members. You should try with pointers to 'a' and polymorphism.
Jun 9, 2009 at 4:55pm
Out of curiousity you wouldn't happen to be writting a game inventory system would you?
Jun 9, 2009 at 4:56pm
I don't believe that this will work UNLESS you use pointers. An object of type b cannot be cast into an object of type a. What you want to do is have a vector of type a pointers.
Jun 9, 2009 at 6:16pm
Yeah, you have to use pointers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class A
{
    int x;
};

class B : public A
{
    int y;
};

int main()
{
   vector<A*> listOfStuff;
   B* b = new B;
   listOfStuff.push_back( b );
   //...
}

Jun 10, 2009 at 3:23pm
@return 0: Yes actually, was it obvious from Item and Itemtype?

Thanks everyone, i understand it better now. Annoyingly, I can't use pointers, I've tried learning but i have sort of mental block and I never understand. Still, no harm in trying again.
Topic archived. No new replies allowed.