0

I am new to c++ , what stuck me is if define a virtual function in the private part of the base class and same function is overridden in child class which is in public section still its giving compiler error below is the code

#include<iostream> 
using namespace std; 

class Base 
{ 
    int x; 
    virtual void fun()
    {
    }
  public: 

    int getX() { return x; } 
}; 

// This class inherits from Base and implements fun() 
class Derived: public Base 
{ 
    int y; 
  public: 
    void fun() { cout << "fun() called"; } 
}; 

int main(void) 
{ 
    Base *d = new Derived; 
    d->fun(); 
    return 0; 
} 

When vtable is created it will contain the overridden function in it, so while calling it it should invoke the child class overridden function, which is public. Why is it giving an error?

bruno
  • 32,421
  • 7
  • 25
  • 37

2 Answers2

2

in

Base *d = new Derived; d->fun();

the static type of d is Base, and in Base fun is private, that's all

If you want to not allow to call fun on Base and because its definition does nothing aperhaps you can declare it public and pure virtual ( virtual void fun() = 0; ), of course doing that you cannot instantiate a Base, you need to instantiate only child of Base

bruno
  • 32,421
  • 7
  • 25
  • 37
  • In addition to this answer, I would suggest reading through [this other SO question](https://stackoverflow.com/questions/3970279/what-is-the-point-of-a-private-pure-virtual-function/3970378) and its accepted answer. It provides a lot of insight into the use of private virtual functions (pure or not). – Tim Klein Jan 12 '19 at 13:58
0

Private members of a class cannot be accessed by derived classes. You need to make it public or protected.

Given that virtual functions main purpose is to provide an API to clients of the class, making them private defeats the design intent of the language.

VorpalSword
  • 1,223
  • 2
  • 10
  • 25
  • having _fun_ protected in _Base_ will not allow to call it, the call is done in _main_, it must be public for that – bruno Jan 12 '19 at 13:57
  • The problem in the question isn't about accessing the private member from a derived class. It's about accessing it through a pointer to the base type. – Pete Becker Jan 12 '19 at 14:04