views:

734

answers:

5

I am having dependency troubles. I have two classes: Graphic and Image. Each one has its own .cpp and .h files. I am declaring them as the following:

Graphic.h:


    #include "Image.h"
    class Image;
    class Graphic {
      ...
    };
`Image.h`:

    #include "Graphic.h"
    class Graphic;
    class Image : public Graphic {
      ...
    };
When I try to compile, I get the following error:
    Image.h:12: error: expected class-name before ‘{’ token

If I remove the forward declaration of Graphic from Image.h I get the following error:

    Image.h:13: error: invalid use of incomplete type ‘struct Graphic’
    Image.h:10: error: forward declaration of ‘struct Graphic’
+2  A: 

You don't need to include Image.h or forward declare Image in Graphic.h - that's a circular dependency. If Graphic.h depends on anything in Image.h you need to split that out into a third header. (If Graphic has an Image member, that just isn't going to work.)

marijne
How does Graphic.h depend on Image.h?
marijne
+1  A: 

Since Image extends Graphic, remove the inclusion of Image in your Graphic.h file.

Graphic.h

class Graphic {
  ...
};
Bill the Lizard
I tried that, it still gives the same error.
Steven Oxley
What compiler are you using? I hate to say WoMM, but...
Bill the Lizard
Also add header guards, then you have the best solution.
Martin York
A: 

First remove this, you must always have the complete class definition available in order to inherit from a class:

class Graphic;

Second, remove all references to Image from Graphic.h. The parent will usually not need to know of its childs.

divideandconquer.se
I tried removing the forward declaration, as was stated in the question.
Steven Oxley
+5  A: 

This worked for me:

Image.h:

#ifndef I_H
#define I_H

#include "Graphic.h"
class Image : public Graphic {

};

#endif

Graphic.h:

#ifndef G_H
#define G_H

#include "Image.h"

class Graphic {
};

#endif

The following code compiles with no error:

#include "Graphic.h"

int main()
{
  return 0;
}
Claudiu
+1  A: 

Graphic.h doesn't need to include image.h, and it doesn't need to forward declare the Image class. Also, Image.h doesn't need to forward declare the Graphic class since you #include the file that defines that class (as you must).

Graphic.h:

class Graphic {
  ...
};

Image.h:

#include "Graphic.h"
class Image : public Graphic {
  ...
};
John Dibling