0

I learnt that declaring a class as a friend class enables it to use the contents or members of the class in which it is declared. I used the following code:

#include <iostream>

using namespace std;

class two; // forward class declaration
class one {
private:
    friend class two; // friend class declared
    int a; // to be accessed later
public:
    one() { a = 5; }
};

class two {
private:
    int b;

public:
    two() {
        b = a; // intended to access 'a' and assign to 'b'
        cout << " " << b << endl;
    }
};

int main() {
    one one_obj;
    two two_obj;
    return 0;
}

Error is: 'a' was not declared in this scope

What I've noticed in most examples of friend class is that constructor 'two()' will use 'class one' as the argument and later use the data member 'a'. But I wouldn't always want to make a new object as an argument to constructor two(). For example, calling constructor one() has already been done and the value of 'a' has already been set. Making a new object would mean doing that again, which might not be favorable. So what it all leads to is that, can I access members of class using friend class but without having to declare an object once again?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user3124361
  • 471
  • 5
  • 21
  • You meant `friend class two;` there. Also, it's unclear what you're asking. Indeed friendship does not imply you have to take the other class as a constructor parameter. I hope that helps. – sehe Jan 17 '15 at 01:39
  • yeah I actually meant friend class two. it`s been fixed. I wanted to know how to assign the value of 'a' to 'b'. – user3124361 Jan 17 '15 at 01:42
  • 2
    You'd first need to have that value `a`. Your problem isn't with friendship. Your problem is that no instance of class `a` actually exists (or is in scope where you seem to want one) – sehe Jan 17 '15 at 01:43
  • thanks, I wished to know whether there was any way I could get values without using class instances. But as you stated that I need one. Changed my code to use an instance of class. – user3124361 Jan 17 '15 at 02:01

2 Answers2

1

Class two being a friend of class one only overrides the access checking.

It still means you must actually refer to a static member of the class, or a non-static member of a specific instance of the class the normal way.

You might profit from choosing a tutorial or book from The definitive C++ book list, and reading up about it all.

Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
0
b = a; // intended to access 'a' and assign to 'b'

Just because it is friend you cannot directly access it's members. You need to create one object to access it's members.

one o;
b = o.a; //now it should work 
Pranit Kothari
  • 9,721
  • 10
  • 61
  • 137