Base Class Pointer with Derived Object

Base class has some virtual method and derived class has a method with the same name. If we initialize the base class pointer with derived object, calling of that virtual method will result in which method being called?

Questions by dilzmail

Showing Answers 1 - 15 of 15 Answers

Which version of the function to be called is based upon the type of object pointed by the pointer.This determination of call is made at run time.As your question says the pointer is pointed to the derived object.So the call will be based upon the object pointed and in ur case it is the derived class function.

Execute the following programm and you will be clear.

#include<iostream>
#include<conio.h>

using namespace std;
class base
{
      public:
             virtual void display()
             {
                     cout<<"display function in base class"<<endl;
                    
                     }
};

class derived:public base
{
      public:
            
             void display()
             {
                  cout<<"dislay function in derived class"<<endl;
                  }
                  };
                 
                 
                 
                  int main()
                  {
                      base *bptr;
                      derived d1;
                      bptr=&d1;
                      bptr->display();
                      getch();
                      return 0;
                      }
                 


ans:;dislay function in derived class

ajrobb

  • Sep 22nd, 2010
 

This is polymorphism, an object with at least one virtual method. When a polymorphic object is constructed, it includes a hidden vtable containing virtual function pointers and other polymorphic information. When a virtual method is invoked, it is called through the function pointer in the vtable.

When defining a polymorphic class, the first method I define would be a virtual destructor in the base class. Once a method is defined as virtual in a base class it will be virtual in a derived class. However, it is good manners to include the 'virtual' keyword in the derived class as it documents the intended polymorphism.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions