
please wait
class base { int i,j; public: base(){} base(int _i,int _j):i(_i),j(_j){} virtual void show() {std::cout<<"Base"<<i<<j;} }; class derived:public base { int i,j; public: derived(int _i,int _j):i(_i),j(_j){} void show() {std::cout<<"Derived"<<i<<j;} }; int main() { derived *d_ptr=dynamic_cast<derived*>(new base(1,2)); d_ptr->show();// This point throws access violation error return 0; } |
Base12 |
new base(1,2)
creates object of the base class. Then dynamic_cast<derived*>(new base(1,2))
tries to switch to the interface of the more powerful derived class. It can not, so it returns null pointer. Then d_ptr->show();
fails with access violation, because it calls function on a null pointer. Using static_cast
instead permits, incorrectly, upgrading the interface to derived
. In this case, d_ptr->show();
calls the function void derived::show()
on object of dynamic type base
. derived::show
tries to access derived::i
and derived::j
. But d_ptr
is actually pointing at object of class base
. So, only base::i
and base::j
are present and those are different from the aforementioned. Basically, the function show
reads random stuff from the memory after the object, but the program finishes execution, for what its worth.
|
|
i
and j
from your base class. The variables with the same name from your derived class hide the ones from the base class, but use separate storage. What I mean is, you don't have to reintroduce variables from your base class into your derived class.base *b_ptr=static_cast<base*>(new derived(1,2));
is ok and better.