Inheritance alternatives?

Hey there!
I have a class called `Item`, and another class called `Container`, which inherits `Item`.

I add all `Item` objects to a vector<Item>. When adding a `Container` object to this vector, it works. But when trying to retrieve elements from it, they are only `Item`s, and not `Containers`.

What alternatives are there?
All I can think of right now is copy-pasting all the `Container` methods and fields into the `Item` class definition, but only using them if the item type is that of a Container item.
give virtual functions a look over. I need sample code to understand what you are trying to do.
here's some pseudocode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Item
{
        //item specific stuff
};
 
class Container : public Item
{
        //container specific stuff
}
 
std::vector<Item> itemList;
 
int main()
{
        Container newContainer;
        itemList.push_back(newContainer); //this works
        itemList.at(0).CONTAINER_SPECIFIC_FUNCTION(); //this doesnt work
}
It's just the header that is messing up your classes...
std::vector<Item> itemList;
This has to match up above each of your classes...
look up vector template syntax or related items...

also that second function doesn't work because it requires an argument.
Last edited on
Sorry, but I don't think you understood what I'm trying to do...
Also, how do you know the second function needs an argument when 1) it's pseudo-code, and 2) it's not defined anywhere ?
Did you mean use Item as container of Container object ? And you cant access Container attributes
Line 16 only "works" because all the Container specific data is being tossed out (see "object slicing"), which I suspect you don't want. I think you actually want a vector of pointers to Items so you can take advantage of polymorphism.

In any case, I think you may be approaching the problem incorrectly; the point of making an Item class is so if you want to handle an Item, you can also handle Containers and any other derived classes. But you can't know which specific derived class you are ever operating on, so you can only work with what is defined in Item. So it doesn't make sense to try to call a Container-specific function; what would that do if, say, the actual object there was a Table or something instead?
intuition, lol. that is always the reason. besides it doesn't sound like a user input. and it doesn't sound like an embedded function. maybe it works somehow though. It's true I don't see the whole picture.

honestly, i think you have to create a base class to inherent items class and container class.


Topic archived. No new replies allowed.