C ++: header file not recognizing class

1

I'm working with several classes, and to organize myself better, I put each class in a different file.

actor.h

#ifndef ACTOR_H
#define ACTOR_H

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

#include "collision.h"
#include "world.h"

class Actor
{
    (...)
};

world.h

#ifndef WORLD_H
#define WORLD_H

#include "actor.h"

class World
{
public:
    (...)
    Actor* getActor(std::string id); //Erro aqui
    (...)
};

But I'm getting the following error:

C:\Users\Felipe\Desktop\Joguinho v2\source\world.h|38|error: 'Actor' does not name a type|

Does anyone have any idea of the reason for the error?

    
asked by anonymous 04.06.2017 / 01:32

2 answers

2

In C has a concept called forward declaration . I know this concept for functions, where I can declare the existence of the function to, at a later time, explain how the implementation is.

In C++ , this concept applies to classes as well. This answer in International Stack Overflow deals precisely with your problem (cyclic dependency between classes) using the class declaration as forward declaration . The original answer also provides many interesting details of how the compiler works, I'll summarize here how to avoid these problems in a pragmatic way.

In order to reference a class (such as pointer or reference), it must be declared first. For your case of actors in a world, we can put the classes of this semantic level in the same header and code files.

To use this way, do so in the header:

#ifndef WORLD_ACTORS_H
#define WORLD_ACTORS_H

class Actor; // apenas a forward declaration, sem implementação 
class World; // idem

// real código relativo à classe Actor 
class Actor {
    ...
}

class World {
    Actor* getActor(std::string id);
    ...
}

In the code file, just include the header described above and be happy.

If you want to continue using classes in separate files (which is fair), you need to declare in the World header the Actor class (with forward declaration ); as Actor depends on World, also do forward declaration of World class.

    
04.06.2017 / 02:18
1

Start here: place semicolons after the class declaration ... all class declarations need a semicolon at the end.

class Actor
{
   (...)
}; //<------------------------------------

Edition:

Okay, since the commas have been hit so now you can accept the answer put by "@Jefferson Quesado" and use forward declarations, because the error is being caused by recursive includes:

actor.h

#include "world.h" // <---------------------------------

world.h

#include "actor.h" // <------------------------
    
04.06.2017 / 04:34