Base class
class Base
{
public:
Base()=default;
virtual void f(){cout << "base class\n";}
virtual ~Base(){}
};
Derived class
class Derive : public Base
{
public:
Derive()=default;
void f() override {cout << "derived class\n";}
};
main function
int main()
{
Base* bsd = new Base;
Derive* dru = new Derive;
if(Derive* drd=dynamic_cast<Derive*>(bsd)){
drd->f();
cout << "downcast successful\n";
}else{
cout << "downcast failed\n";
}
if(Base* bsu=dynamic_cast<Base*>(dru)){
bsu->f();
cout << "upcast successful\n";
}else{
cout << "upcast failed\n";
}
delete bsd;
delete dru;
}
It turns out upcast works fine, while downcast failed. It seems makes sense that way. If the derived class contain member objects that are not declared in the base class and do not have default constructors, what gonna happen during downcast?
Besides, the target pointer *drd(*bsd)
created through dynamic_cast
points to the same object with the pointer *bsu(*dru)
to be cast. So delete once will be enough. We will not have a dangling pointer, right?