Friend classes in different header files?


Hi everyone

I am building a very easy example in order to understand the basics of classes.
I made two classes: CVector and CFriend (CFriend being a friend of CVector), with their respective .h and .cpp files. In the main.cpp file, I include both CVector.h and CFriend.h.

I am getting lots of errors because CVector.h understands that the CFriend class has not been declared, and viceversa

My question is: how can I somehow declare the class CVector in the CFriend.h file?

Here the .cpp, .h and main files

/////HEADER FILE CVector.h////////////////////
#include <iostream>

class CVector {
public:
int x, y, z;
CVector (int, int, int);
CVector () {};
CVector operator + (CVector);
friend class CFriend;

};



//////HEADER FILE CFriend.h////////////////////
#include <iostream>

class CFriend {
public:
int xcopy;
CFriend();
void copy_x(CVector);
};


/////MAIN FILE main.cpp////////////////////
#include "CVector.h"
#include "CFriend.h"

using namespace std;

int main (int argc, char * const argv[]) {
CVector vector1(3, 1, 2);
CVector vector2(1, 2, 2);
CVector vectorSum;
vectorSum= vector1 + vector2;
cout << "Suma vectores = " << vectorSum.x << ',' << vectorSum.y << ',' << vectorSum.z << endl;

CFriend amigo;
amigo.copy_x(vector1);
cout << "Copy of x param of vector1 = "<< amigo.xcopy << endl;
return 0;
}


/////////////////
Thanks in advance for the help!


to declare a class write class MyClass; in you header. If an error wold tell you to define a class you should write #include "MyClas.h" (here MyClass is either CVector or CFriend). I'm not sure which one you need here, I rarely use friendship.
For more info on when to include and when to forward declare see http://www.cplusplus.com/forum/articles/10627/
Hope this helps
Please use code tags: http://cplusplus.com/articles/firedraco1/


As for your question: CFriend.h should forward declare CVector:

1
2
3
4
5
6
7
8
9
10
11
//////HEADER FILE CFriend.h////////////////////
#include <iostream>

class CVector;  // <-  This line

class CFriend {
public:
int xcopy;
CFriend();
void copy_x(CVector);
};


Also -- you shouldn't be #including <iostream> in CVector.h or CFriend.h, as it's unnecessary for those classes.

Obligatory link to relevent article:

http://cplusplus.com/forum/articles/10627/

Specifically, see sections 3 and 4.
Thanks hamsterman and Disch for the answers!
Topic archived. No new replies allowed.