I am confused about the term upcasting in c++ (for example here). Is it really a casting? For example when I cast a an int
to a double
, I expect the casted type to behave exactly as a double
. However, if I upcast a derived class to a base class it seems the casted object doesn't behave exactly as an object of the base class as the following code shows :
class Base {
public:
virtual void print() { cout << "base" << endl; }
};
class Derived :public Base {
public:
void print() { cout << "derived" << endl; }
};
void main()
{
// Upcasting
Derived d;
Base* pBase = &d;
// test
Base b;
Base* pBase2 = &b;
if (dynamic_cast<Derived*>(pBase));
{
cout << "1st upcasting ok" << endl;
}
if (dynamic_cast<Derived*>(pBase2))
{
cout << "2nd ucasting ok" << endl;
}
}
output :
1st upcasting ok