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?

Member Avatar for Siersan

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();
}

Thank you.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.