#include problems

I have three header files (and associated cpp files as well, of course) like the following:

calculator.h:
1
2
3
4
5
6
7
8
9
10
11
#ifndef CALCULATOR_H
#define CALCULATOR_H

#include "ui_calculator.h"

class calculator
{
   //various standard class stuff here
};

#endif // CALCULATOR_H 


ui_calculator.h:
1
2
3
4
5
6
7
8
9
#ifndef UI_CALCULATOR_H
#define UI_CALCULATOR_H

#include "calcentrywidget.h"

class Ui_calculator{
 //yada yada yada
};
{


and, finally, calcentrywidget.h:
1
2
3
4
5
6
7
8
9
#ifndef CALCENTRYWIDGET_H
#define CALCENTRYWIDGET_H

class calcEntryWidget
{
    //various class members
};

#endif // CALCENTRYWIDGET_H 


This all works well, compiles, runs, everyone is happy. Now I want to add a pointer to a calculator object to my calcEntryWidget class - basically a pointer back to its parent object. So, obviously, I have to add a #include "calculator.h" to the calcentrywidget.h file. And everything falls apart - the instant I add that #include, having made no other changes, compilation fails with a
ISO C++ forbids declaration of 'calcEntryWidget' with no type
error, followed by a slew of other errors stemming, I believe, from that one. What am I missing here? How can I add a calculator pointer to the calcEntryWidget class? Thanks.
Last edited on
Forward declare calculator in calcentrywidget.h. You don't need to include the entire header for it.
Well, that seems to work, except that I still need to include calculator.h in the calentrywidget.cpp file for it to compile. So I needed the forward declaration in the header, and the include in the cpp. Is that right? Seems a bit redundant, but maybe that's just the way it is supposed to work. Thanks!
Yes, that is the way it is supposed to work.

In general, if all you do is declare a pointer-to-type or reference-to-type in your header file, then you can and should forward declare type rather than include its header file. This not only helps eliminate circular inclusion problems (which in a large system can be much harder to find) but also helps reduce compile times (assuming dependencies are used).

Topic archived. No new replies allowed.