Why can't member function be friend?

I

Immortal_Nephi

I want to show you an example how two classes can have relationship
instead of an inheritance. The inheritance is not an option if you
want to define two classes.
The relationship between two classes can be friends when variables
can be modified in both classes. As far as we discussed in an earlier
post, but I try to make this code much clearer.
The C++ Compiler generates an error if you try member function to be
friend because member function has not defined yet.
Only one member function can modify variable in another class. It
prevents you to add more member functions to modify variables in
another class. You may not want to use "friend class" as your best
option.
Do you have a way to fix an error?

Here is my example code here.

#ifndef CLASS_A_H
#define CLASS_A_H

class B;

class A
{
public:
A();
~A();
void Modify_A(B &b);
friend void B::Modify_B(A &); // error C2027: use of undefined type
'B'

private:
// friend class B;
int m_A1;
int m_A2;
};

#endif // CLASS_A_H


#ifndef CLASS_B_H
#define CLASS_B_H

class A;

class B
{
public:
B();
~B();
void Modify_B(A &a);
friend void A::Modify_A(B &); // error C2027: use of undefined type
'A'

private:
// friend class A;
int m_B1;
int m_B2;
};

#endif // CLASS_B_H


// CLASS_A.CPP
#include "Class_A.h"
#include "Class_B.h"

A::A() : m_A1(0), m_A2(0)
{
}

A::~A()
{
}

void A::Modify_A(B &b)
{
b.m_B1 += 3;
b.m_B2 += 4;
}


// CLASS_B.CPP
#include "Class_B.h"
#include "Class_A.h"

B::B() : m_B1(0), m_B2(0)
{
}

B::~B()
{
}

void B::Modify_B(A &a)
{
a.m_A1 += 1;
a.m_A2 += 2;
}


// MAIN.CPP

#include "Class_A.h"
#include "Class_B.h"

int main(void)
{
A a;
B b;

a.Modify_A(b);
b.Modify_B(a);

return 0;
}

Nephi
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top