Friday, March 26, 2010

Can derived pointer point to base class object ?

Ans: Yes we have to cast it .without cast it will not get compiled .
g++ error: invalid conversion from `base*' to `der1*'
 Remember dynamic_cast will not work (it disallows base to derived casting ). Use Static cast or Reinterpret cast.
Exmaple
 der1* obj1 =  static_cast < der1* > (new base()) ;

Now Question comes in mind what if i call a new function(which is not in Base ) defined in Derived class form this Derived pointer (which is Actually points to Base object ) .

I thought it should not allow But it got compiled and ran successfully .

What if I wand to access public member variable by same Derived pointer (which is Actually points to Base object ) .  Remember derived object is not created . 
i thought it should core dump But its accessing variables and printing Garbage value .
Output : base::print
base::k
der1::nonvirtual :9
value of derived var 8

1 comment:

Followers