inheritance - Downcasting a class c++ -


i have doubt downcasting object in c++.

here comes example:

class { } class b : public {    public:     void setval(int i) { _v = i; }   private:     int _v; }  a* = new a(); b* b = dynamic_cast<b*>(a); b->setval(2); 

what happen example? modifying base clase if child one... how work related memory?

with cast... creating instance of b , copying values of a?

thanks

a* a; 

this gives pointer a. doesn't point anywhere in particular. doesn't point @ a or b object @ all. whether code works or not depends on dynamic type of object pointing at.

so there 2 situations might want know about. first, one:

a* = new a(); b* b = dynamic_cast<b*>(a); b->setval(2); 

this give undefined behaviour because dynamic_cast return null pointer. returns null pointer when dynamic type of object not b. in case, object a. attempt dereference null pointer b->setval(2), undefined behaviour.

a* = new b(); b* b = dynamic_cast<b*>(a); b->setval(2); 

this work fine because object b object. dynamic cast succeed , setval call work fine.

however, note work, a must polymorphic type. true, must have @ least 1 virtual member function.


Comments