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.
In C++, a friend function or friend class can also access private data members. So, is it possible to access private members outside a class without friend? Yes, it is possible using pointers.
Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of a class.
A friend function cannot access the private and protected data members of the class directly. It needs to make use of a class object and then access the members using the dot operator. A friend function can be a global function or a member of another class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With