Unix C++
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Friend Class

2 posters

Go down

Friend Class Empty Friend Class

Post by Christopher 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.
Christopher
Christopher
Admin

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

https://unixcpp.forumotion.com

Back to top Go down

Friend Class Empty hii

Post by Vineet_More 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

Back to top Go down

Friend Class Empty Re: Friend Class

Post by Christopher 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"
Christopher
Christopher
Admin

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

https://unixcpp.forumotion.com

Back to top Go down

Friend Class Empty 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