Friend Class

Go down

Friend Class

Post by Christopher on Tue Mar 02, 2010 5:03 pm

Code:
#include<iostream.h>

using namespace std;

class Sample
{
   int a;

public:

   Sample(int a)
   {
      this->a=a;
   }

   int getA()
   {
      return a;
   }

   friend class Test;
};

class Test
{

public:

   Test(Sample* obj,int a)
   {
      obj->a=a;
   }

};

int main()
{
   Sample s(20);
   Test t(&s,30);
   cout<<"Changed value of a : "<<s.getA();
}


Test is a friend class of Sample. So Test can access private members of Sample. In this example Test access private member 'a' of Sample.
avatar
Christopher
Admin

Posts : 240
Points : 429
Join date : 2010-02-26
Age : 30

View user profile http://unixcpp.forumotion.com

Back to top Go down

hii

Post by Vineet_More on Tue Mar 02, 2010 7:08 pm

I think a friend class can alos be used to access the protected member of the base class.

Vineet_More

Posts : 27
Points : 31
Join date : 2010-02-26

View user profile

Back to top Go down

Re: Friend Class

Post by Christopher on Wed Mar 03, 2010 10:04 am

yes.. friend class can access all the members of the class.

In this example "Test" can access private, protected and public members of "Sample"
avatar
Christopher
Admin

Posts : 240
Points : 429
Join date : 2010-02-26
Age : 30

View user profile http://unixcpp.forumotion.com

Back to top Go down

Re: Friend Class

Post by Sponsored content


Sponsored content


Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum