Is it possible to access the members of a child class when looping though a vector?
struct Object
{
std::string name;
};
struct Rect : Object
{
int x;
int y;
int width;
int height;
};
struct Circle : Object
{
int x;
int y;
int radius;
}
Running the code below gives me the error struct Object has no member named 'x'
which I'm guessing is because auto&
sees it as an Object
. Is there any way for the iterator to use the Rect
members?
int main()
{
std::vector<Object> objects;
Rect r;
r.name = "test";
r.x = 1;
r.y = 1;
objects.push_back(r);
for(auto& ob: objects)
{
std::cout << ob.x << std::endl;
}
return 0;
}