class Item{
public:
//other codes
virtualvoid ShowData(){}
}
class Electronic: public Item{
//getters and setters
void ShowData()
}
class Book: public Item{
//getters and setters
void ShowData()
}
class Other: public Item{
//getters and setters
void ShowData()
}
//ShowData just a simple method to show all data members
int main(int argc, char *argv[]){
vector<Item> items;
Item *item;
item = new Electronic();
item->SetName("Iphone");
item->SetPrice(1000);
items.push_back(item);
items[i].ShowData();
}
Codes above shows nothing, can someone help me?? he problem is pushed item...
This could be to do with the way you're using the vector. You're copying your Electronic objects into objects of type Item, so the objects in the vector won't "know" which subclass they were copied from.
You ought to make your vector a vector of Item* pointers instead.
The object between the angle-brackets states what sort of object you're putting into the vector. So in your original:
vector<Item> items;
defined a vector that contains objects of type Item.
vector<Item*> items;
would, instead, declare a vector that contains objects of type Item*, i.e. a vector that contains pointers.
Obviously, you'll need to change those parts of your code that use the vector elements so that they work with pointers, such as line 34 of your original code.