I have a base class A
and a derived class B
.
class A {
public:
int x;
virtual int getX() {
return x;
}
};
class B : public A {
public:
int y;
};
The virtual function is there just to make it polymorphic.
Next i declare a list of A
's but put B
's inside:
vector<A> list;
B b1,b2;
b1.y = 2;
b2.x = 10;
list.push_back(b1);
list.push_back(b2);
Now i want to go over all elements on the vector and access the y
member (which only B
's have):
for (auto it = list.begin(); it != list.end(); ++it) {
B &cast = dynamic_cast<B&>(*it);
int value = cast.y;
std::cout << value << std::endl;
}
This code gives a runtime error. Any idea how can i do the cast and access y
?