Search code examples
c++inheritanceorganization

How do you inherit from a class in a different header file?


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;
    }