2 Replies - 5629 Views - Last Post: 17 February 2006 - 05:36 PM Rate Topic: -----

#1 henry  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 96
  • Joined: 03-January 06

Friend function in classes

Posted 16 February 2006 - 09:38 PM

How to applied friend function in the classes?
let say

Class One{
private:

public:

};

Class Two{
private:


public:


};

1.I want to mmake this two classes to be friends
How can I do so?
2. Is there need Class Three to be the intermediate class between the classes?
to access the data between the 2 classes or
let say Class One is friennd to Class Two so Class One can access the data in the Class two so no need intermediate class.....

Can you all tell me much about it?
Thank you
remember to smile............

Is This A Good Question/Topic? 0
  • +

Replies To: Friend function in classes

#2 Voodoo Doll  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 12
  • View blog
  • Posts: 108
  • Joined: 24-January 06

Re: Friend function in classes

Posted 17 February 2006 - 08:22 AM

You're the one who says who can look at your privates, right? :) The same goes with classes. If you want class B to access class A's private data, class A is the one that declares class B as a friend:
#include <iostream>

class A {
  friend class B;
private:
  int a;
};

class B {
public:
  B(int a) { myA.a = a; }
  void printA() { std::cout << myA.a << '\n'; }
private:
  A myA;
};

int main()
{
  B myB(10);

  myB.printA();
}


At that point any object of B can access the private data in an object of A, but only internally. So you can't say 'myB.myA.a = 20;' in main or you'll get an error. That is, unless you also make main a friend of both classes because both B::myA and A::a are private:
#include <iostream>

class A {
  friend class B;
  friend int main();
private:
  int a;
};

class B {
  friend int main();
public:
  B(int a) { myA.a = a; }
  void printA() { std::cout << myA.a << '\n'; }
private:
  A myA;
};

int main()
{
  B myB(10);

  myB.myA.a = 20;
  myB.printA();
}


Was This Post Helpful? 1
  • +
  • -

#3 Videege  Icon User is offline

  • rvant.toujours
  • member icon

Reputation: 6
  • View blog
  • Posts: 1,413
  • Joined: 25-March 03

Re: Friend function in classes

Posted 17 February 2006 - 05:36 PM

well done voodoo
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1