I am just trying to understand the virtual fns. concept.
I know that if I have a virtual fn. in a base class and its overridden fn. in derived class then based upon the address of base/derived object stored in the base class pointer the fns. will be called.
In the below code I had kept the show() fn. as virtual and it used to call properly the base and derived classes show().
But when I removed the virtual tag from show() then why does not it calls derived show() inspite of base class pointer having address of derived class object?
class base
{
public:
base()
{
printf("Base Cons\n");
}
void show()
{
printf("Base Show\n");
}
};
class der: public base
{
public:
der()
{
printf("Der Cons\n");
}
void show()
{
printf("Der Show\n");
}
};
void yahoo(base* bpointer)
{
printf("Address in base pointer = %u\n",bpointer);
bpointer->show();
}
int _tmain(int argc, _TCHAR* argv[])
{
class base bobj, *bptr;
class der dobj;
bptr = & bobj;
printf("Base obj adress = %u\n",&bobj);
yahoo(bptr);
bptr = &dobj;
printf("Base obj adress = %u\n",&dobj);
yahoo(bptr);
return 0;
}
Output of code:
Base Cons
Base Cons
Der Cons
Base obj adress = 1245027
Address in base pointer = 1245027
Base Show
Base obj adress = 1245003
Address in base pointer = 1245003
Base Show