Can you override private functions defined in a base class?

nitin_cherian picture nitin_cherian · Nov 12, 2011 · Viewed 38.8k times · Source

I believe, a derived class can override only those functions which it inherited from the base class. Is my understanding correct.?

That is if base class has a public member function say, func, then the derived class can override the member function func.

But if the base class has a private member function say, foo, then the derived class cannot override the member function foo.

Am i right?

Edit

I have come up with a code sample after studying the answers given by SO members. I am mentioning the points which i studied as comments in the code. Hope i am right. Thanks

/* Points to ponder:
   1. Irrespective of the access specifier, the member functions can be override in base class.
      But we cannot directly access the overriden function. It has to be invoked using a public
      member function of base class.
   2. A base class pointer holding the derived class obj's address can access only those members which
      the derived class inherited from the base class. */

#include <iostream>

using namespace std;


class base
{
   private:
      virtual void do_op()
      {
         cout << "This is do_op() in base which is pvt\n";
      }

   public:
      void op()
      {
         do_op();
      }
};

class derived: public base
{
   public:
      void do_op()
      {
         cout << "This is do_op() in derived class\n";
      }
};

int main()
{
   base *bptr;
   derived d;

   bptr = &d;
   bptr->op(); /* Invoking the overriden do_op() of derived class through the public 
               function op() of base class */ 
   //bptr->do_op(); /* Error. bptr trying to access a member function which derived class 
                    did not inherit from base class */            

   return 0;
}

Answer

Xeo picture Xeo · Nov 12, 2011

You can override functions regardless of access specifiers. That's also the heart of the non-virtual interface idiom. The only requirement is of course that they are virtual.