PolarBear
PolarBear

Reputation: 342

Basic polymorphism

I have two structs:

struct X { double x; };

struct Y : X { double y; };

I want a vector filled with basic objects (of type X) which possibly can be extended (to objects of type Y):

    std::vector<X*> vec;

    if(condition)
    {
        for(size_t i=0; i<n; ++i)
        {
            vec.push_back(new Y);
            vec[i]->x = ...;
            vec[i]->y = ...; // error
        }
    }
    else
    {
        for(size_t i=0; i<n; ++i)
        {
            vec.push_back(new X);
            vec[i]->x = ...;
        }
    }

This gives the error " no member named 'y' in 'X' ". Do you know how I could achieve what I wish?

Upvotes: 2

Views: 90

Answers (1)

Sebastian
Sebastian

Reputation: 1974

Quick solution for the code you posted so far. Change

vec.push_back(new Y);
vec[i]->x = ...;
vec[i]->y = ...; // error

to

Y* newy = new Y;
vec.push_back(newy);
newy->x = ...;
newy->y = ...; // no error

But then you will still need a cast of X* to Y* when reading the object back to access the member variables only contained in Y.

if(condition)
    cout << static_cast<Y*>(vec[i])->y;

Instead of casts you could also create separate vectors for X and Y (do not need to be pointers, if they contain only the one type, but could also be the pointers) and just fill and access one of them.

vector<X> vecX;
vector<Y> vecY;
bool condition;

Upvotes: 1

Related Questions