Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of undefined type [duplicate]

Tags:

c++

#include <iostream>

class Core;
class State;

int main (){
        std::cin.get();
        return 0;
}

class State{
public:
    State(Core* core){
        core->setState();
    }
};

class Core{
public:
    Core(){
        State state(this);
    }
    void setState(){
        std::cout << "setting state" << std::endl;
    }
};

I keep getting the "use of undefined type" error. I thought that if I forward declare both of the classes, it would fix the problem but I can't figure it out. Is it just silly c++ syntax that I'm missing?

EDIT: Sorry about the gamestate typo, I've changed it to State and it still produces the error.

like image 336
Ben Avatar asked Aug 17 '13 02:08

Ben


1 Answers

In State::State, you are using Core before it is actually defined. You can fix this easily in your example by moving the constructor implementation out of the class definition:

class State{
public:
    State(Core* core);
};

class Core{
   // This stays the same...
};

State::State(Core* core)
{
   core->setState();
}

It's much more common in practice to have the implementation of these functions in a separate implementation (.cpp) files, in which case the forward declarations would work as you've expected.

In that case:

// State.h
class Core;

class State{
public:
    State(Core* core);
};

And

// Core.h
#include "State.h"
#include <iostream> //This is probably a good reason to further separate
                    //Core.h into Core.h and Core.cpp

class Core{
public:
    Core(){
        State state(this);
    }

    void setState(){
        std::cout << "setting state" << std::endl;
    }
};

And the implementation file:

// State.cpp
#include "State.h"
#include "Core.h"

State::State(Core* core)
{
   core->setState();
}
like image 116
Chad Avatar answered Oct 18 '22 07:10

Chad