0

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?

Edited by Nick Evan: n/a

3
Contributors
3
Replies
4
Views
12 Years
Discussion Span
Last Post by Abivino
0

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

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.