yurec wrote:
I want to know waht do you think about my assumptions.Are they
correct?
At least one of them isn't: you assume we remember what you
posted about.
If you want to ask a follow-up question, quote enough of the
original discussion so at least some context is retained.
V
--
On Dec 3, 6:23 pm, Rahul <sam_...@yahoo.co.in> wrote:
Hi Everyone,
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?
Thanks in advance!!!
In first case (with virtual method) both classes have pointer to
virtual method table.
With reinterpret_cst you say to compiler to work with Base, as it has
memory layout as Derived class.
When you call ptr->sample() you do following :
1)get pointer to virtual table of the class ( which has the same place
in the object memory for Base and Derive, but different value)
2)call the first ( as Derived has single virtual method as Base does)
method from virtual table, which is Base::Sample.
If you remove virtual method from base class, both will not have any
pointer to virtual method table.So
When you call ptr->sample() you do following :
1)Get the address of Derived::sample and run it successfully, because
it doesn't refer to any of Derived members or methods
P.S. Some assumptions regarding second step, correct me please, if i'm
wrong :
There is special table for Derived methods ( for non virtual methods).
When you call ptr->sample(), you go to that table, find appropriate
function and give to this
function pointer to Base class as a parameter.- Hide quoted text -
- Show quoted text -