-
include problem
I need to include a .h file that has already been included in another file. Because I cant include the same .h files in two different classes, I am stuck.
The following is an example of what I mean:
Code:
#include "a.h"
int main()
{
AClass aObj;
aObj.someFnct();
return 0;
}
The a.h file
Code:
#include "b.h"
#include "x.h"
class AClass
{
...
...
BClass bObj;
XClass xObj;
void someFnct ();
};
//-------------------------
void AClass::someFnct ()
{
bObj.foo();
...
...
xObj.problemFnct (bObj);
}
The b.h file
Code:
const int MAX = 50;
class BClass
{
int num;
char str[MAX];
...
...
void foo();
};
//-------------------------
void BClass::foo ()
{
AClass aObj; <-- ???
...
...
}
The x.h file
Code:
template <class T>
class XClass
{
...
...
void problemFnct(T &data);
};
//-------------------------
template <class T>
void XClass::problemFnct(T &data);
{
AClass aObj; <-- ???
...
...
aObj.someFnct(); <-- ???
}
How can I call a function or create an object that belongs to AClass from classes B and X :confused:
-
Only solution I can think of right now is to merge the header files together. You should also remove the function definitions from the header file and put them in seperate .cpp files, for example:
Code:
//b.cpp
#include "abx.h" //merged headers
//-------------------------
void BClass::foo ()
{
AClass aObj; <-- ???
...
...
}
-
The actual files are separated..but I just kept it as one for example purposes. As for the merged headers...what is a merged header??
-
Sorry, I should've been clearer. I just meant to put all the class declarations in one header file:
Code:
//abx.h
class AClass
{
...
...
BClass bObj;
XClass xObj;
void someFnct ();
};
const int MAX = 50;
class BClass
{
int num;
char str[MAX];
...
...
void foo();
};
template <class T>
class XClass
{
...
...
void problemFnct(T &data);
};
And then of course include that file in the .cpp files
-
Another, slightly more complicated solution is to use the Pimpl idiom (a.k.a. compilation firewall). The idea is that in your header file, you don't have any data members except one. That member is a pointer to a struct that is not defined in the header file. Since you can have a pointer to an undefined class or struct, you can define that struct in the cpp file.
Code:
// MyClass.h
class MyClass
{
// ... Public Interface
private:
struct Impl;
Impl* pimpl;
};
// MyClass.cpp
#include "MyClass.h"
// All your other header includes
struct MyClass::Impl
{
// Data members
};
MyClass::MyClass() : pimpl(new Impl) { }
MyClass::~MyClass() { delete pimpl; }
Then in the rest of your code, you refer to data members as pimpl->datamembername. Anyway, you should probably read up on it for more information than this, but that is the basic idea.