Marc,
Here is how I interpret what you are saying:
br as a base reference to an instance of Derived
Code:
class Base
{
public:
Base() {};
virtual ~Base() {}
};
class Derived : public Base
{
public:
Derived() {}
virtual ~Derived() {}
};
int main()
{
Base base;
Derived derived;
Base& br = derived;
try {
Derived& dr = dynamic_cast<Derived&>(br);
} catch (const bad_cast&) {
cout << "Bad cast!\n";
}
return 0;
}
The dynamic_cast will work, and it does.
However, if br is really a Base reference to an instance of Base, then the dynamic_cast will throw an exception.
Code:
class Base
{
public:
Base() {};
virtual ~Base() {}
};
class Derived : public Base
{
public:
Derived() {}
virtual ~Derived() {}
};
int main()
{
Base base;
Derived derived;
Base& br = base;
try {
Derived& dr = dynamic_cast<Derived&>(br);
} catch (const bad_cast&) {
cout << "Bad cast!\n";
}
return 0;
}
Yes, the above throws an exception. But, what is the statement doing to make it throw an exception? I don't see the illegality. I see a downcast.