In C ++, how can we call a private function through an object without using a friend function?

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;
}

Conclusion:

 Derived::fun(int x) called 

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 this is happening? In the first case, a private function is called through the object.

+5
source share
2 answers

Polymorphism occurs in the first case. This causes dynamic or late binding. And, as mentioned in the second answer, from time to time it can become quite dangerous.

. friend, , . . .

 int call_fun (int i) ;

fun() .

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

, , wrapper functions.

friends . .

+3

Base, , Derived. , .

+4

All Articles