You cannot. Your code has an undefined behavior. If I modify the main()
function to:
int main()
{
Person *p = new Person();
Developer* d = dynamic_cast<Developer*>(p);
assert(d!=0);
d->Pi();
delete p;
delete d;
return 0;
}
Then the assertion d!=0
is triggered. That shows that the dynamic_cast
failed. You call Developer::Pi
on a null pointer, and using your compiler it happens to run fine, probably because Developer::Pi
does not use this
.
1
solved Derived class’s method without constructor [duplicate]