R@M3$H.NBlog

Call Base class method through base class pointer pointing to derived class

20 January, 2014 - 2 min read

How to call Base class method through base class pointer pointing to derived class

   1: class Base

   2: {

   3:   public:

   4:     virtual void foo()

   5:     {}

   6: };

   7:

   8: class Derived: public Base

   9: {

  10:   public:

  11:     virtual void foo()

  12:     {}

  13: };

  14:

  15: int main()

  16: {

  17:     Base *pBase = NULL;

  18:     Base objBase;

  19:     Derived objDerived;

  20:

  21:     pBase = &objDerived;

  22:     pBase->foo();

  23:

  24:     /*Here Derived class foo will be called, but i want this to call 

  25:     a base class foo. Is there any way for this to happen? i.e. through 

  26:     casting or something? */

  27: }

You can do it through scope resolution operator ::

Something like this:

pBase->Base::foo()