0

I'm trying to have an boost::container::vector containing instances of a few class that all inherit from the same superclass, and then have some functions only apply to the instances of a specific class, but I can't seem to get it to work.

This is the first time I try this, so maybe I just made a rookie mistake, can one of you tell me where I went wrong, and why ?

Here's an example code :

using boost::container::vector;

class card{
public:
    card(int aa,int bb):a(aa),b(bb){}
    virtual ~card(){}
    int a,b;
};
bool operator==(card l, card r){ return l.a==r.a; }
bool operator<(card l, card r){
    if(l.a<r.a){ return true;}
    else{ return l.b<r.b; }
}
std::ostream& operator<<(std::ostream& os, card c){
    os << c.a << ":" << c.b;
    return os;
}

class subcard:public card{
public:
    subcard(int a, int b):card(a,b){}
    virtual ~subcard(){}
    int c=0;
};



int main() {
    cout << "Hello, World!" << endl;
    vector<card> v1;
    v1.push_back(card(2,2));
    v1.push_back(subcard(1,1));
    for (int i = 0; i < v1.size(); ++i) {
        cout<<v1[i]<<endl;
    }
    for (int i = 0; i < v1.size(); ++i) {
        if(subcard* sc = dynamic_cast<subcard*>(&(v1[i]))){
            cout<< "found : " << sc <<endl;
        }
    }
    return 0;
}

Thank you very much :)

1 Answers1

1

Read about object slicing.

In short: Each element in your vector only has enough space to hold a card object. When you push_back a subcard object, the subcard part of that object gets "sliced" away, and it becomes a card.

There's no way to get back that lost information. Effectively, there's no way to find out whether that card was originally a subcard (i.e. dynamic_cast<subcard*>(&(v1[i])) won't work here).

You need to store references or pointers in the vector to avoid slicing. In your case a std::vector<std::reference_wrapper<card>> (since you can't store raw references in a vector) seems suitable.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Thank you. I had seen object slicing, but didn't get a solution from it, just an understanding of my problem. I finally used pointers rather than reference_wrapper to store, and it works fine now :) – user3187114 Jun 20 '15 at 12:32