6
#include <iostream>

class B;

class A{
 int a;
public:
 friend void B::frndA();
};

class B{
 int b;
public:
 void frndA();
};

void B::frndA(){
 A obj;
 std::cout << "A.a = " << obj.a << std::endl;
}

int main() {
 return 0;
}

When trying to compile this code, some errors occurred. E.g.

invalid use of incomplete type

What are the problems in this code?

Disillusioned
  • 13,820
  • 3
  • 39
  • 75
Arif
  • 927
  • 11
  • 29
  • 2
    I've retagged the question. `friend` isn't one of the most helpful keywords. Also `forward-declaration` makes more sense when combined in one tag. Edit: Oh and `class` also makes more sense then `function` I guess :) – Ivo Wetzel Jul 06 '10 at 05:38

3 Answers3

3

Place the whole of the class B ... declaration before class A. You haven't declared B::frndA(); yet.

#include <iostream>
using namespace std;

class B{
    int b;
public:
    void frndA();
};

class A{
    int a;
public:
    friend void B::frndA();
};



void B::frndA(){
    A obj;
    //cout<<"A.a = "<<obj.a<<endl;
}

int main() {
    return 0;
}
Anthony
  • 11,352
  • 9
  • 65
  • 100
3

The problem is you can't friend a member function before the compiler has seen the declaration.

You are going to need to rearrange your code to solve the problem (i.e. move the definition of class B prior to class A).

R Samuel Klatchko
  • 70,693
  • 15
  • 126
  • 182
2

You need to put the declaration of B before A. The compiler doesn't know about this: B::frndA(). A forward declaration is not enough information to infer what members the type has.

I would recommend to put your class A declaration in a file A.h and it's definition inside a file A.cpp. Likewise the same for the type B inside of B.h and B.cpp

At the top of each header file put #pragma once (or if you prefer include guards).

Then inside your B.h you can simply include A.h.

Brian R. Bondy
  • 314,085
  • 114
  • 576
  • 619
  • 1
    In fact, pragma once can fail when the same file falls within different search paths since it's based on the path and not on the content of the file. – Edward Strange Jul 06 '10 at 06:20
  • pragma once is supported by all major compilers. I don't think #pragma once warrants the down vote. See here: http://stackoverflow.com/questions/1143936/pragma-once-vs-include-guards/1143958#1143958 – Brian R. Bondy Jul 06 '10 at 06:25