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?
double y;fromYtoXX*. It can’t accessYmembers through that pointer. So keep the actual type:Y* ptr = new Y; ptr->y = ...; vex.push_back(ptr);.dynamic_castwon’t work unless the base type has one or more virtual functions.static_castwould work if you know that theX*in fact points at an object of typeY.