2

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?

12
  • Polymorphism is for behaviour, usually. Looks like you need composition, maybe? Commented Apr 5, 2020 at 21:54
  • Move double y; from Y to X Commented Apr 5, 2020 at 21:55
  • 2
    The immediate problem is that the code stores an X*. It can’t access Y members through that pointer. So keep the actual type: Y* ptr = new Y; ptr->y = ...; vex.push_back(ptr);. Commented Apr 5, 2020 at 22:01
  • 1
    @AdrianMole — dynamic_cast won’t work unless the base type has one or more virtual functions. Commented Apr 5, 2020 at 22:03
  • 2
    @AdrianMole — yes static_cast would work if you know that the X* in fact points at an object of type Y. Commented Apr 5, 2020 at 22:09

1 Answer 1

1

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; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.