reaching friend function

Here is my code:
1
2
3
4
5
6
7
8
9
10
class A{
void FA1();
friend class B;
};

class B{
void FB1(){
A::FA1(); // *from here
}
};

I need to access FA1 from *. But i don't want to use 'static' to declare any of them. Actually i found this:
1
2
3
//inside class B
A * x1=0;
x1->FA1();

instead of
A::FA1();
but I need more reliable code because there may be some changes at x1 or something else.
You have a slight misunderstanding of member functions.

A member member function does something with (or to) an object of the given type. For example... FA1() in your above code is a member of the A class. Therefore, it would logically do something with an A object.

Here's a little code to illustrate:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class A
{
  int member;
public:
  void set(int v)
  {
    member = v; // changes 'member' of 'this' object
    // ie, this->member
  }
};

int main()
{
  A example;
  example.set( 5 );  // sets because we're calling A::set with 'example'
   // 'example' becomes 'this'.  Therefore 'example.v' is changed by this line

  // this, however, is a compiler error:
  A::set( 3 ); // this doesn't make any sense because there's no object.  Whose 'v' are we changing here?
    // we can't change an object's variable when we don't have an object.
}


This is the problem with your code. You're trying to call an A member function without an A object, which doesn't make any sense.

This is even worse:
1
2
A * x1=0;
x1->FA1();


This makes 'this' a null pointer (ie, you'll be accessing invalid memory -- which will probably crash your program).


If the function does NOT need an object in order to work, then that's when you make the member function static. That's exactly what static member functions are for.
Actually, it's perfectly fine to pass a null this to a member function. As long as the function doesn't dereference this to access data, that is.
Or if the function specifically checks for a null this pointer or something... yeah.

I doubt that's the case here, though.
Topic archived. No new replies allowed.