Sunday, 26 October 2014

Calling Base Class Virtual Method using Derived class object


Below are couple of ways to achieve calling a base class virtual method using  derived class object
  
Implementation 1

 #include<iostream>
using namespace std;
class Base
{
      public:
             virtual void Check()
             {
                     cout<<"Calling Base";
             }
};
class Derived:public Base
{
      public:
             void Check()
             {
                    cout<<"Calling Derived";
             }
};
int main()
{
    Derived d;
    d.Base::Check(); // Qualified Id
     return 0;
   
}

Implementation 2

#include<iostream>
using namespace std;
class Base
{
      public:
             virtual void Check()
             {
                     cout<<"Calling Base";
             }
};
class Derived:public Base
{
      public:
             void Check()
             {
                  Base::Check();
              }
};
int main()
{
    Derived d;
    d.Check();
    return 0;
   
}
 


Output (in both 1 and 2):
Calling Base

Please comment if you find anything incorrect.

No comments:

Post a Comment