Question

I came across this code written in C++ :

#include<iostream>
using namespace std;

class Base {
public:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};

class Derived: public Base {
private:
    int fun(int x)   { cout << "Derived::fun(int x) called"; }
};

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

Output:

 Derived::fun(int x) called 

While in the following case :

#include<iostream>
using namespace std;

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

class Derived: public Base {
private:
    int fun(int x)   {  }
};
int main()
{
    Derived d;
    d.fun(1);
    return 0;
} 

Output :

Compiler Error.

Can anyone explain why is this happening ? In the first case , a private function is being called through an object.

Was it helpful?

Solution

Polymorphism is happening in the first case. It causes dynamic or late binding. And as mentioned in the second answer, it can become quite dangerous at times.

You cannot access the private interface of a class from the outside of class definition directly. If you want to access the private function in the second instance without using a friend function, as title of your question implies, make another public function in your class. Use that function to call this private function. Like this.

 int call_fun (int i) ;

Call the fun() from inside it.

int call_fun (int i)
{
  return fun (i) ;  //something of this sort, not too good
}

The functions like this which are used just to call another function are known as wrapper functions.

Making friends is also not advisable always. It is against the principle of information hiding.

OTHER TIPS

Because in the first case you're using declaration from Base, which is public, and the call is being late-bound to the Derived implementation. Note that changing the access specifier in inheritance is dangerous and can nearly always be avoided.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top