954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Friend classes?

A rather old C++ book I have says that one class may be declared a friend class of a second, and then the first class can access the private data of the second. I tried this example

#include <iostream.h>

class secret
{    friend class not;
       private :
        int a;
};

class not
{   public:
     not (int x) // constructor
     {  secret.a = x;}
      void printout()
       {   cout << secret.a << endl; }
};

main()
{    not testclass(4);
      testclass.printout();
}


The compiler didn't like "secret.a" nor was it happier when I relaced it by just 'a'. Anyone familiar with the friend classes?

murschech
Junior Poster in Training
60 posts since Dec 2004
Reputation Points: 21
Solved Threads: 1
 

You need an object of class secret or to derive from secret before you can access it's members. Just because you define a friend doesn't mean the rules of C++ have changed.

#include <iostream>

using namespace std;

class secret
{
  friend class no_secret;
  int a;
};

class no_secret
{
  secret s;
public:
  no_secret (int x) // constructor
  { 
    s.a = x;
  }
  void printout()
  { 
    cout << s.a << endl; 
  }
};

int main()
{ 
  no_secret testclass(4);
  testclass.printout();
}
Siersan
Light Poster
45 posts since Jan 2005
Reputation Points: 12
Solved Threads: 2
 

Thank you.

murschech
Junior Poster in Training
60 posts since Dec 2004
Reputation Points: 21
Solved Threads: 1
 

It is a rule in c++ that all data members and member functions of a class should be accessed only with the help of objects.The same is done in C structures where we access structure members with the help of structure variables.

Abivino
Newbie Poster
1 post since Mar 2010
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You