PDA

View Full Version : association between 2 classes



castorvert
25th March 2006, 14:45
Hello,
I have 2 classes A and N, and I want an association between them.

Here is the code :



#include "a.h"
#include "n.h"
int main()
{
A* a=new A();
N* n=new N(a);
A->setN(n);
}





#ifndef A_H
#define A_H

#include "n.h"

class A{

N* _n;

public :
A(){}
void setN(N* n){_n=n;
}

};
#endif



#ifndef N_H
#define N_H


#include "a.h"
class N{

A* _a;

public :
N(A* a):_a(a){} <--- syntax error*: ')'



};
#endif
I have a problem at the compilation ...

jacek
25th March 2006, 15:46
Move the implementation to .cpp files and replace #include with forward declarations.

Beluvius
2nd April 2006, 12:32
The problem here is the infinite recursion of the dependencies in the header files. You cannot include a header file in a header file that includes that header file (read this line again, it makes sense). So, basically, you should either make:
- a.h independent of n.h
- n.h independent of a.h
- a.h independent of n.h and n.h independent of a.h

This is only needed for header files, not for .cpp files! The .cpp files may include both header files, no problems there ever.
You don't have to move the implementation to the source files in this case. Pointers can be used in header files without knowing the contents of classes N or A. (As a benefit, your compilation will speed up if you use a class definition, but sometimes it is not that handy)

So, the following works:
a.h:


#ifndef A_H
#define A_H

class N;

class A{
N* _n;
public :
A(){}
void setN(N* n){_n=n;
}
};
#endif

n.h


#ifndef N_H
#define N_H

class A;

class N{
A* _a;
public :
N(A* a):_a(a){}
};
#endif


And you can keep main.cpp the same.

Beluvius.

Michiel
5th April 2006, 06:39
I once planned to do everything with forward declarations, hoping it would be a universal solution. :) But how do I do this with classes that use templates?

Oh well, if I can't I can't. I can make an exception in that case if I have to.

Beluvius
5th April 2006, 08:52
Don't make it a general rule to use forward declarations. It can be used in many many cases, but sometimes it is simply very usefull to include the actual header file.

With templates, you can be in luck depending on the implementation. As the template functions are only expanded when called, the conflict may or may not be there. If you do have problems, you should either unlink the two classes, or make a 'master' class which handles the communication between the two classes. I probably don't have to advise you to prevent 2 classes being linked to eachother ;)