Vector inheritance question

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.
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.
Out of curiousity you wouldn't happen to be writting a game inventory system would you?
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.
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 );
   //...
}

@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.