QED
QED

Reputation: 77

Using friend function in C++

Just read about friend functions and I'm trying to access private variable "number" in class A with friend function "Print" from class B. I'm working with Visual Studio. Compilation of my code gives me plenty of various errors like:

C2011: 'A' : 'class' type redefinition
C2653: 'B' : is not a class or namespace name

Please be patient with me me and show a proper way of achieving my goal.

Here are my files A.h:

class A
{
public:
    A(int a);
    friend void B::Print(A &obj);
private:
    int number;
};

A.cpp:

#include "A.h"

A::A(int a)
{
    number=a;
}

B.h:

#include <iostream>
using namespace std;
#include "A.h"
class B
{
public:
    B(void);
    void Print(A &obj);
};

B.cpp:

#include "B.h"

B::B(void){}

void B::Print(A &obj)
{
    cout<<obj.number<<endl;
}

main.cpp:

#include <iostream>
#include <conio.h>
#include "B.h"
#include "A.h"

void main()
{
    A a_object(10);
    B b_object;
    b_object.Print(A &obj);
    _getch();
}

Upvotes: 2

Views: 1537

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

... Second you might need a forward declaration of class B in the A.h header file to refer B as a friend:

#ifndef _A_H_
#define _A_H_
class B;

class A
{
     friend class B;
};
#endif

UPDATE
I'm currently not so sure if it's possible to declare member functions as friends, I'll have a look.

It's not possible to create member function friend declarations, you can either declare global functions or whole classes as friend, see also: C++ ref, Friendship and inheritance.

In general it's not a good design idea to use friend at all, because it strongly couples the classes together. The better solution will be to couple interfaces (which don't need to be publicly visible anyways).
In rare cases it might be a good design decision but that almost always applies to internal details.

Upvotes: 3

pbhd
pbhd

Reputation: 4467

First you need to put

#ifndef A_H
#define A_H
.... your A-class definition
#endif

in your A.h and analogous in B.h, so that multiple includes of the same file is prevented (that is your duplicate definition error)...

Upvotes: 1

Related Questions