Reputation: 1444
First of all this is not 'homework', its a problem from Thinking in C++ Vol 1, chapter 5 ex 5. I need to make 3 classes, the first granting friendship of its internals to the whole second class, and friendship to only a function from the third class.
I dont have a problem with granting friendship to the entire 2nd class, but with granting to the third class function, if i declare the third class in the same header theres no problem. But in different headers i get some undefined type / declaration. Thanks for your help and here is the code:
#ifndef FIRSTCLASS_H
#define FIRSTCLASS_H
//firstclasss header file
#include "secondclass.h"
#include "thirdclass.h"
class secondclass; //dummy declaration so it can share friendship
class thirdclass; //it doesnt work when i want to give friendship to a function
class firstclass{
private:
int a;
int b;
public:
friend secondclass; //granting friendship to the whole class
friend void thirdclass::z(firstclass *); //error
//use of undefined type 'thirdclass'
//see declaration of 'thirdclass'
};
#endif FIRSTCLASS_H
#ifndef THIRDCLASS_H
#define THIRDCLASS_H
//thirdclass header file
#include "firstclass.h"
class firstclass;
class thirdclass{
public:
void z(firstclass *);
};
#endif THIRDCLASS_H
Upvotes: 2
Views: 151
Reputation: 726809
You need to provide forward declarations only when you are not including the header for the corresponding class. Since you are including both secondclass.h
and thirdclass.h
already, you should skip the corresponding forward declarations altogether.
In the thirdclass.h
, however, you do not need firstclass.h
: you are declaring a pointer to firstclass
, not using its members, so you do not need an include.
The general rule is that you should forward-declare your classes if all you need is a pointer, and include their headers when you need knowledge of the members of the class.
Upvotes: 2
Reputation: 3522
Remove the inclusion of firstclass.h that is in thirdclass.h. It it causing firstclass to be defined before third class. Beware of recursive includes.
To see when classes actually are getting defined (depending on your compiler), add #pragma messages before the actual class definitions.
Upvotes: 0