How do you inherit from a class in a different header file?
-
05-07-2019 - |
Question
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’
Solution
This worked for me:
Image.h:
#ifndef IMAGE_H
#define IMAGE_H
#include "Graphic.h"
class Image : public Graphic {
};
#endif
Graphic.h:
#ifndef GRAPHIC_H
#define GRAPHIC_H
#include "Image.h"
class Graphic {
};
#endif
The following code compiles with no error:
#include "Graphic.h"
int main()
{
return 0;
}
OTHER TIPS
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.)
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 {
...
};
Since Image extends Graphic, remove the inclusion of Image in your Graphic.h file.
Graphic.h
class Graphic {
...
};
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.