Search code examples
c++forward-declarationc2079

Forward Declaration: Undefined Class ( C2079 )


I have an error in my code. All the forums says "in this situation, use Forward Declaration". I tried this and it don't work.

the error is C2079 Credit::mainMenu use a class of MainMenu not declared (translated from french)

I modified the classe to be specific to the question.

main.cpp

#include <SFML/Graphics.hpp>

#include "Menu.h"

#include "credit.h"
#include "mainmenu.h"


MainMenu *mainMenu = new MainMenu();//works here

int main(){
    return 0;
}

credit.h

#ifndef DEF_CREDIT
#define DEF_CREDIT

#include <SFML/Graphics.hpp>
#include "Menu.h"
class MainMenu;


class Credit : public Menu
{
private:
    MainMenu mainMenu = MainMenu();//DON'T WORK HERE
};

#endif

mainmenu.h

#ifndef DEF_MAINMENU
#define DEF_MAINMENU

#include <SFML/Graphics.hpp>
#include "Menu.h"
#include "credit.h"

class MainMenu :public Menu
{
private:
    Credit credit = Credit();//work
};
#endif

Fist i load main.cpp after the credit.h (there is a credit.hpp but i don't use the variable now) after the mainmenu.h (there is also a mainmenu.hpp, i don't use variable now)

tip: the Menu class isn't including any of those class

I can send you the complete code if you want

Thanks in advence!


Solution

  • This issue is know as circular dependency. Long story short, two objects should never have another as its subobject.

    Instead you have two options. One is to have one point to another

    class Credit : public Menu
    {
    private:
        MainMenu* mainMenu;
    };
    

    Or, you could have a manager of sorts, where only the manager is aware of both objects, and let them interact through the manager

    class Manager
    {
    private:
        Credit credit;
        MainMenu mainMenu;
    };
    

    For the technical reason why you can't have a member of a declared but not defined type is because it is a incomplete type, and you can't have an object of incomplete type.