Tuesday, May 29, 2012

Access member variable from non member function in C++

Friend non member function can access private member variable also. following example help you to understand how to use friend keyword and how to access member private variables from non member function.

#include <stdio.h>

class Woman{
//making it friend
friend void loveWoman();

private:
 int age;
 int salary;

public:
 char name[50];
 void walk();
};

//friend function
void loveWoman(){
 Woman myGirlFriend;

 // access private member variables
 printf("My girlfriends age:%i \n",myGirlFriend.age);

 // access public member variables
 printf("My girlfriends age:%i \n",myGirlFriend.name);
}

//not a friend function
void hateWoman(){
 Woman myhusbandXWife;

 // only can access public member variables
 printf("My girlfriends age:%i \n",myhusbandXWife.name);
}

void main(){
 //call friend non member function
 loveWoman();

 //call non member function
 hateWoman();
}




2 comments: