So after some research I have been struggling to have separate class header and source code for my inheritance classes. The following examples are shortened versions of my classes. All of my headers have include guards, default constructors and virtual destructors. They also have getter and setter functions as needed for the variables. I will mainly just show the variables and the includes.
MainProgram.h
#include "FileMgr.h"
#include "InfoMgr.h"
class FileMgr;
class InfoMgr;
class MainProgram
{
private:
FileMgr* fileMgr;
InfoMgr* infoMgr;
public:
.
.
.
}; // !MainProgram
MainProgram.cpp
#include "MainProgram.h"
#include <iostream>
MgrBase.h
#include "MainProgram.h"
#include <string>
class MainProgram;
class MgrBase
{
protected:
MainProgram* mainProgram;
MgrBase() : mainProgram(nullptr) {}
virtual ~MgrBase() {}
public:
virtual bool Init() = 0;
}; // !MgrBase
FileMgr.h
#include "MgrBase.h"
class MainProgram;
class FileMgr : public MgrBase
{
public:
FileMgr(MainProgram* mainProgram);
.
.
.
};// !FileMgr
FileMgr.cpp
#include <iostream>
#include <string>
#include "FileMgr.h"
#include "MainProgram.h"
InfoMgr.h
#include <string>
#include "MgrBase.h"
class MainProgram;
class InfoMgr : public MgrBase
{
public:
InfoMgr(MainProgram* mainProgram);
.
.
.
}; //!InfoMgr
InfoMgr.cpp
#include <iostream>
#include "MainProgram.h"
#include "InfoMgr.h"
So I have tried figuring out the class declarations and includes but I'm not getting it. With the way the code is now, I get this error on the '{' following class InfoMgr : public MgrBase:
error: expected class-name before ‘{’ token
If I make InfoMgr.h look like
#include <string>
//Class Foward Declarations
class MainProgram;
class MgrBase;
and InfoMgr.cpp look like
#include <iostream>
#include "MainProgram.h"
#include "InfoMgr.h"
#include "MgrBase.h"
I get this error in reference to the line class InfoMgr : public MgrBase
error: invalid use of incomplete type ‘class MgrBase’
If I make it so the InfoMgr.cpp doesn't include MgrBase and make it so InfoMgr.h looks like this:
#include <string>
#include "MgrBase.h"
//Class Forward Declarations
class MainProgram;
class MgrBase;
I get this error in reference to the line class InfoMgr : public MgrBase
error: invalid use of incomplete type ‘class MgrBase’
You have a cycle in your header inclusion:
MainProgram.h
includes FileMgr.h
FileMgr.h
includes MgrBase.h
MgrBase.h
includes MainProgram.h
You need to break this cycle using forward declarations.
The rule in header files should be: if you only need to declare reference or pointer to a type X
, forward declare X
instead of including the header which defines it. The same applies if you're declaring (not defining) a function which has a parameter or return value of type X
.
You only have to include the full definition of X
if you're accessing members of X
or defining a class derived from X
.
In your case:
#include
statements from MainProgram.h
to MainProgram.cpp
#include "MainProgram.h"
from MgrBase.h