Yes, I know that downcast using dynamic_cast
can't compile if the Base
is not polymorphic, but my problem is not about this.
class Base {
public:
virtual void bar()
{
cout << "bar\n";
}
};
class Derived: public Base {
public:
void foo()
{
cout << "foo\n";
}
};
int main()
{
Base *pb;
Derived *pd;
pb = new Derived; //Base* points to a Derived object
pd = dynamic_cast<Derived*>(pb);
pd->foo(); //outputs foo
pb = new Base; //Base* points to a Base object
pd = dynamic_cast<Derived*>(pb);
pd->foo(); //outputs foo, too. Why?
}
I thought when pb = new Derived;
, pb
actually points to a Derived
object lies in heap. After pd = dynamic_cast<Derived*>(pb);
, pd
also points to that Derived
object, so pd->foo()
should be OK.
But when pb = new Base;
, what pb
points to is a Base
object in heap, then after pd = dynamic_cast<Derived*>(pb);
, how could pd->foo()
works? Did dynamic_cast
turn the Base
object in heap into a Derived
object?