In the main
function below , the first static_cast
is valid as i am trying to cast a (base class reference to Derived1
class) to a derived reference
But why is the second cast printing with the values, though it prints junk value for d2.y
, i assumed it should be a warning or compilation error.
How is a base reference to base object picking derived class's value (d2.y
in this case, i can also assign a value to it )
Can someone please explain what happens in these two cases .
class Base1
{
public:
Base1()
{
x = 999;
}
int x;
};
class Derived1: public Base1
{
public:
Derived1()
{
y = 1000;
}
int y;
};
int main()
{
Derived1 d;
std::cout << d.x << " " << d.y << std::endl;
Base1& b = d;
Base1 b1;
Base1 & b2 = b1;
Derived1& d1 = static_cast<Derived1&>(b);
Derived1& d2 = static_cast<Derived1&>(b2);
std::cout << d1.x << " " << d1.y << std::endl;
std::cout << d2.x << " " << d2.y << std::endl;
return 0;
}