0

I 've got a collision issue. I mean that in my A.h in need to include B.h but in B.h I need to include A.h so I can't figure out how to fixe it.

Interface.h

#ifndef _INTERFACE_H
#define _INTERFACE_H

#include <SDL.h>
#include <vector>
#include "Widget.h"

class Interface
{
public:
    Interface(SDL_Rect &r);
    ~Interface();
private:
    SDL_Rect m_rect;
    std::vector<Widget*> m_widgets; 
};

#endif

Widget.h

#ifndef _WIDGET_H
#define _WIDGET_H

#include <SDL.h>
#include "Interface.h"

class Widget
{
public:
    Widget(Interface *main, SDL_Rect &r);
    ~Widget();
private:
    SDL_Rect m_rect;
    Interface* m_master; 
};

#endif
icetomtom
  • 25
  • 1
  • 5

3 Answers3

1

Since you rely on pointers, you can declare (rather than define) the classes, and include the header files in the cpp files:

#ifndef _INTERFACE_H
#define _INTERFACE_H

#include <SDL.h>
#include <vector>

class Widget; //See the swap from include to declaration?

class Interface
{
public:
    Interface(SDL_Rect &r);
    ~Interface();
private:
    SDL_Rect m_rect;
    std::vector<Widget*> m_widgets; 
};

#endif

Do a similar swap in the other header.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
1

That's not a "collosion" but a circular dependency.

For your case it's solved very easily by not including the header files at all, and only use forward declarations of the classes:

File Interface.h:

#ifndef INTERFACE_H
#define INTERFACE_H

#include <SDL.h>
#include <vector>

// No inclusion of Widget.h
// Forward declare the class instead
class Widget;

class Interface
{
public:
    Interface(SDL_Rect &r);
    ~Interface();
private:
    SDL_Rect m_rect;
    std::vector<Widget*> m_widgets; 
};

#endif

File Widget.h:

#ifndef WIDGET_H
#define WIDGET_H

#include <SDL.h>

// Don't include Interface.h
// Forward declare it instead
class Interface;

class Widget
{
public:
    Widget(Interface *main, SDL_Rect &r);
    ~Widget();
private:
    SDL_Rect m_rect;
    Interface* m_master; 
};

#endif

You of course needs to include the header files in your source files.


Also note that I changed the symbols for your include guards. Symbols with a leading underscore followed by an upper-case letter are reserved in all scopes by the "implementation" (the compiler and standard library). See this old question and its answers for details.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

EDIT: Doctorlove was faster.

use forward declaration in one of the files:

#ifndef _INTERFACE_H
#define _INTERFACE_H

#include <SDL.h>
#include <vector>
#include "Widget.h"

class Widget;

class Interface
{.....

#endif