Salt_Peter
10/11/2008 2:02:00 PM
On Oct 11, 6:42 am, Pranav <pranav...@gmail.com> wrote:
> include <iostream>
> #include <unistd.h>
> #include <stdlib.h>
>
> class base{
> public :
> virtual void disp(){ std::cout << "Base Class\n";}
> void show(){ std::cout << "Base Show\n"; }
>
> };
>
> class derived:public base{
> public :
> void disp(){ std::cout << "Derived Class\n"; }
> void show(){ std::cout << "Derived Show\n";}
>
> };
>
> int main()
> {
> base *bptr;
> derived *dptr = new derived;
> bptr = (base *)dptr;
>
> bptr->disp();
>
> return 0;
>
> }
>
> Why does the bptr call derived version?? Even though I type casted
> it..,
The pointer is pointing to an object, the fact that the pointer is
pointing to the base portion of that instance doesn't change the fact
that you are pointing to a derived object.
> I know virtual func are called according to the type of object pointed
> by the but not according to the type of pointer used to point to the
> object,
It doesn't matter how you attempt to masquerade your base pointer, in
the end its the object that executes the virtual function call.
Picture some Animals in a series of cages. If you ask the 3rd Animal
(a cat) to talk(), would you expect anything less than a 'meaowww'?
Its not the pointer talking, its the cat.