Rahul wrote:
I was just playing around virtual functions and landed up with the
following,
class Base1
{
public: virtual void sample()
{
printf("base::sample\n");
};
};
class Derived1: public Base1
{
public: void sample()
{
printf("derived::sample\n");
};
};
int main()
{
Derived1 *ptr = reinterpret_cast<Derived1 *> (new Base1());
ptr->sample();
return(0);
}
this invokes the sample() of base version, but if i declare sample as
a ordinay (non-virtual) function, the sample() of derived class is
invoked. I'm wondering how? Can anyone help in this regard?
The code 'ptr->sample()' has undefined behaviour because casting from
a base class to a derived class is NOT what 'reinterpret_cast' is for.
Either 'static_cast' or 'dynamic_cast' are used for that.
In your case 'dynamic_cast' should return NULL since the object is
NOT of type 'derived', which should suggest that 'static_cast' is not
what you need either. You only use 'static_cast' in this situation
if you *know exactly* that the pointer was obtained by converting
some derived class object into the base.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask