Puedes seguirnos en



Access private members of a class using a non member function

Is there a way to access the private members of a class by a non member function?. Well there is one way, know as the friend function. This function has access to all private and protected members of the class for which it is a friend.

To declare a friend function, include its prototype in the class of which you want to access the private and public members, preceding it with the keyword friend.



using namespace std;
class myclass
int a,b;
friend int sum(myclass x);
void set_ab(int i, int j);

The function sum is not a member function of any class. Although sum is not a member, it still has full access to its private members.

Anuncio publicitario

The friend functions are not called by the reference of the object created by the class, because it is not a member of the class, so it cannot be qualified with an objects name.

int main()
myclass n;
n.set_ab(3,4);//Call by the reference of the object.
sum(n);//Directly called without reference of the object.

So we can access all the members of a class by a non-member function, if the function is a friend with the class.

Escrito por

Administrador de ENGGDRCAOS. Canal dedicado especialmente a la formación del estudiante que aspira a ser ingeniero. Todos los videos son Ingles. Apasionado del universo Apple, estudiante de Ingeniería y Gamer por vocación.




Function prototyping is one of the key improvements added to the C++ functions. When a function call is encountered, the compiler checks the function...


If we want two computers to communicate over a network, then the protocols on each layer of OSI model in the sending computer should...


When virtual functions are created for implementing late binding, there are some basic rules that satisfy the compiler requirements: The virtual function must be...


In assembly language programs, small sequence of codes of the same pattern are repeated frequently at different places which perform the same operation on...