Why it call Derived ..,

P

Pranav

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..,
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,
 
J

Juha Nieminen

Pranav said:
Why does the bptr call derived version?? Even though I type casted
it..,
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,

First you ask a question and then you answer it. There's nothing left
for us to do.
 
S

Salt_Peter

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.
 
Y

Yakov Gerlovin

Even though 'disp' is not explicitly declared virtual in the derived
class, it is a virtual function,since it is declared so in 'base'.
Omitting 'virtual' keyword in the derived class does not change this.
It is a good practice, however, to use 'virtual' keyword also in
derived classes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top