Cannot call child's method

I have 1 parent (Item) and 3 child classes (Electronic, Book, Other)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Item{
public:
    //other codes 
    virtual void 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...
Last edited on
Can you show us the full implementation of Electronic, so that we can see what might be going wrong?

Last edited on
You have a vector of Item but you inserted an Item*.
@vince yeah that's the problem, but how to fix it? I'm not good with C++ syntax
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.
Last edited on
@MikeyBoy

how to declare it? vector<Item*> ??
Yes, that's right.

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.
Last edited on
oh thank you for your help :D
solved
You're welcome :)
Topic archived. No new replies allowed.