simple friend function not working

S

suresh.amritapuri

Hi,
What is wrong in this simple friend function code?

#include <iostream>
using namespace std;

class B;
class A{
public:
A():aa(10){}
void dispA(){cout << aa << endl;}
private:
int aa;
friend class B;
};

class B{
public:
B():bb(20){}
void dispB(){cout << bb + aa << endl;}
private:
int bb;
};

int main(){

A a;
B b;
b.dispB();
}

compiler (g++) says: testFriend.cpp:17: error: ‘aa’ was not declared
in this scope.

any suggestions?
thanks
suresh
 
I

Ian Collins

suresh.amritapuri said:
Hi,
What is wrong in this simple friend function code?

#include <iostream>
using namespace std;

class B;
class A{
public:
A():aa(10){}
void dispA(){cout << aa << endl;}
private:
int aa;
friend class B;
};

class B{
public:
B():bb(20){}
void dispB(){cout << bb + aa << endl;}
private:
int bb;
};

int main(){

A a;
B b;
b.dispB();
}

compiler (g++) says: testFriend.cpp:17: error: ‘aa’ was not declared
in this scope.

That's correct. There isn't a member of B called aa.

Friendship only grants a class access to another's private parts, it
doesn't include it.
 
J

Jonathan Lee

Hi,
What is wrong in this simple friend function code?

You're trying to use it like you were inheriting. "aa"
is indeed not in scope.

"aa" is not a member of class B. It is a member of class A
and, more to the point wrt B, a member of an *instance* of A.

You would need to change to either:

// Access the member aa of instance x
void dispB(const A& x) { cout << bb + x.aa << endl; }

or drop the friend and inherit A

class B : public A {
// ...
};

Depends on what you're really trying to do. A third
option would be to write a getter for aa. i.e.,
int A::get_aa() const { return aa; } // pick a better name

--Jonathan
 
S

suresh.amritapuri

You're trying to use it like you were inheriting. "aa"
is indeed not in scope.

"aa" is not a member of class B. It is a member of class A
and, more to the point wrt B, a member of an *instance* of A.

You would need to change to either:

  // Access the member aa of instance x
  void dispB(const A& x) { cout << bb + x.aa << endl; }

or drop the friend and inherit A

  class B : public A {
    // ...
  };

Depends on what you're really trying to do. A third
option would be to write a getter for aa. i.e.,
  int A::get_aa() const { return aa; } // pick a better name

--Jonathan

Thank you all, I got the point,
suresh
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top