c++ Base Class Undefined. Including base and subclass in another class - c++

I have a class GameObject which has a vector of Component and Transform.
The Transform is a Component but can be accessed on it's own.
I'm getting a Base class undefined error on Component when I try to include both Component.h and Transform.h in GameObject.
Error Message:
Error 1 error C2504: 'Component' : base class undefined c:\users\pyro\documents\visual studio 2010\projects\engine\main\transform.h 9
GameObject.h
#ifndef _GameObject
#define _GameObject
#include "Core.h"
#include "Component.h"
#include "Transform.h"
class Transform;
class Component;
class GameObject
{
protected:
Transform* transform;
vector<Component*> components;
};
#endif
Component.h
#ifndef _Component
#define _Component
#include "Core.h"
#include "GameObject.h"
class GameObject;
class Component
{
protected:
GameObject* container;
};
#endif
Transform.h
#ifndef _Transform
#define _Transform
#include "Core.h"
#include "Component.h"
//Base class undefined happens here
class Transform : public Component
{
};
#endif
I've found a bunch of other topics, but they don't really address the problem I'm having.
So the question is this: why am I getting this error and how do I fix it?

There are a couple of problems with your code:
1. Circular dependency
GameObject.h includes Component.h, and Component.h includes GameObject.h.
This circular dependency breaks everything. Depending on which file you're "starting from", either GameObject will not be visible from Component or vice versa, due to the inclusion guards.
Remove the circular dependency: you don't really need those #includes at all, as you're already using forward declarations. In general, minimise the use of #include in headers.
2. Syntax error
When you've fixed that, add in the missing }; in Component.h.
(Your definition for Transform thinks it's a nested class inside Component which, at that point, has not been fully defined.)
3. Reserved names
This may not cause you a practical problem today, but your macro names should not begin with _ as these are reserved for implementation (compiler) use.

Suppose some source file has a #include "Component.h" directive and no other #include directives. Here's what happens, in order:
The preprocessor symbol _Component is defined.
The #include "GameObject.h" directive in Component.h is expanded.
The #include "Component.h" directive in GameObject.h is expanded.
This does nothing because _Component is now defined.
The #include "Transform.h" directive in GameObject.h is expanded.
The definition of class Transform in Transform.h won't compile because the base class Component has not been defined yet.
The problem is that you have too many superfluous #include statements. For example, there's no need for GameObject.h to include Component.h. The forward declaration is all that is needed. In general, don't include a file in a header unless you truly do need it. If you do need to do so, you need to be very careful of circular inclusions.

Related

How can I include a header file in, but the header file I include includes the file I want to include

I can't really describe my problem, so I'll show you here with code what I mean:
boxcollider.h
#include "sprite.h"
class BoxCollider
{
public:
BoxCollider(Sprite sprite);
};
sprite.h
#include "boxcollider.h"
class Sprite
{
public:
BoxCollider coll;
};
INCLUDE issue. How can I solve this problem?
You have two issues. One is the circular references between the two classes. The other is just the circular includes. That one is easy.
All your includes -- ALL of them -- should guard against multiple includes. You can do this two ways.
#ifndef BOXCOLLIDER_H
#define BOXCOLLIDER_H
// All your stuff
#endif // BOXCOLLIDER_H
However, all modern C++ compilers I've used support this method:
#pragma once
As the first line in the file. So just put that line at the top of all your include files. That will resolve the circular includes.
It doesn't fix the circular references. You're going to have to use a forward declaration and pass in a reference, pointer, or smart pointer instead of the raw object.
class Sprite;
class BoxCollider
{
public:
BoxCollider(Sprite & sprite);
};
BoxCollider.h should NOT include Sprint.h, but the .CPP file should.
You can solve this issue by using forward referencing. This would work as follows:
boxcollider.h
#ifndef boxcollider(Any word you like but unique to program)
#define boxcollider(same word as used earlier)
#include "sprite.h"
class BoxCollider
{
public:
BoxCollider(Sprite sprite);
};
#endif
sprite.h
#ifndef sprite(Any word you like but unique to program)
#define sprite(same word as used earlier)
class BoxCollider;
class Sprite
{
public:
BoxCollider& coll; // reference or (smart)pointer
};
#endif
Also don't forget the import guards. These prevent you from importing a file more than once.

Undefined base class, though includes present

Forehand I'd like to mention I'm fairly new to C++ programming and that I'm using Ogre3D as framework (for school project reasons).
I have a class Player which inherits from the GameObject class. When trying to build the project I'm confronted with the following error:
Error C2504 'GameObject' : base class undefined - player.h (9)
Which would imply the GameObject class is undefined within the player class' header file. However I have in fact included the GameObject header file in that of the Player (see code below). I am aware circular including is happening in the code. However if I leave out these includes I get a whole list of different errors on which I'm not sure how or why they occur:
I've been stumped on this problem for a few days now and haven't found any solutions around the Internet as of yet (CPlusPlus article I've mainly been consulting: http://www.cplusplus.com/forum/articles/10627/).
The source files for the below listed header files only include their respective header files.
Player.h
#pragma once
#ifndef __Player_h_
#define __Player_h_
#include "GameObject.h"
class Player : public GameObject {
// ... Player class interface
};
#endif
GameObject.h
#pragma once
#ifndef __GameObject_h_
#define __GameObject_h_
#include "GameManager.h"
// Forward declarations
class GameManager;
class GameObject {
// ... GameObject class interface
};
#endinf
The GameObject header includes the GameManager as can be seen.
GameManager.h
#pragma once
// Include guard
#ifndef __GameManager_h_
#define __GameManager_h_
// Includes from project
#include "Main.h"
#include "Constants.h"
#include "GameObject.h" // mentioned circular includes
#include "Player.h" // "
// Includes from system libraries
#include <vector>
// Forward declarations
class GameObject;
class GameManager {
// ... GameManager interface
};
#endif
To top it of there is the Main class which header file looks like the following:
Main.h
// Include guard
#ifndef __Main_h_
#define __Main_h_
// Includes from Ogre framework
#include "Ogre.h"
using namespace Ogre;
// Includes from projet headers
#include "BaseApplication.h"
#include "GameManager.h"
// forward declarations
class GameManager;
class Main : public BaseApplication
{
// ... Main interface
};
#endif
With all the reading I did on the subject and other individuals with the same error I'd figure I would be able to figure it out but yet to no avail. I hope someone can take the time to help me out here and point out any faulty code or conventions.
I think the easiest way to fix the problem is to change your model for including header files. File A.h should only include B.h if B.h defines a symbol that is used (directly) in A.h. It's also generally a bad idea to put a using clause in a header file - let the programmer of the client code make that determination. Drop forward declarations for classes unless they are absolutely necessary; there's no need for the class GameManager right after #include "GameManager.h". I suspect something else is wrong with the code, but the forward declarations for the classes are hiding that problem. If changing the includes does not fix the problem, start with a single .cpp file that includes the "simplest" header (the one that doesn't depend on any others) and build up to the full set of includes.

C++: almost identical header files, but one gives a peculiar inheritance-related error

For a C++-project, I need to make a game with Doodlebugs and Ants, which are both Organisms. So, I made a class called Organism with the following definition (although I'll probably add way more member functions and member variables, of course).
Organism.h:
#ifndef ORGANISM_H
#define ORGANISM_H
#include "World.h"
class Organism
{
public:
Organism();
~Organism();
virtual void Move() = 0;
friend class World;
int survivalTime;
};
#endif
Organisms live in 'the World', which is a class with (among others) a member variable Organism*** field, a two-dimensional dynamic array containing pointers to Organism objects.
World.h:
#ifndef WORLD_H
#define WORLD_H
#include "Organism.h"
#include "Ant.h"
#include "Doodlebug.h"
class World
{
public:
World();
~World();
void gameplay();
Organism*** field;
};
#endif
You probably already guessed it: Ant and Doodlebug are derived from Organism.
Ant.h:
#ifndef ANT_H
#define ANT_H
#include "Organism.h"
class Ant : public Organism
{
public:
Ant();
~Ant();
void Move();
};
#endif
Doodlebug.h:
#ifndef DOODLEBUG_H
#define DOODLEBUG_H
#include "Organism.h"
class Doodlebug : public Organism
{
public:
Doodlebug();
~Doodlebug();
void Move();
};
#endif
As you can see, Ant.h and Doodlebug.h are almost identical, except for the words Doodlebug and Ant. However, I have two errors.
In World.h, line 16: "'Organism' does not name a type."
In Doodlebug.h, line 7: "expected class-name before '{' token"
Why is this? The first error can be solved by putting class Organism; right before the definition of class World, but I don't understand why that changes anything, since the complete definition of Organism is in Organism.h, which I include.
The second error is the one I'm VERY confused by (and kind of the main reason I'm asking this question), since Ant.h is identical to Doodlebug.h except for the words Ant and Doodlebug, but in Doodlebug.h I get an error but not in Ant.h???
Any help is greatly appreciated.
You have circular dependency between World.h and Organism.h.
World.h has
#include "Organism.h"
and Organism.h has
#include "World.h"
You can remove the above line from Organism.h and replace it with a forward declaration.
class World;
Use forward declaration in header files if you don't need the definition of a as a matter of principle. That will not only avoid problems like the one you encountered but it will also reduce compile time dependecies.
Additional references:
Forward declaration vs include
When can I use a forward declaration?
You did not post your compile command (and most importantly what is the file you try to compile?), but below is what I think your problem is.
The main problem is that your Organism.h includes World.h, which in turn tries to include Organism.h once again, but does not actually include it due to include guards. Therefore, in World.h the compiler still does not know what Organism is and thus generates the first error. You can use forward declaration to solve this: just write
class Organism;
in World.h before class World...; you can also remove #include "Organism.h" from World.h.
I suppose that your second problem can be related to this also.
Note that you can use -E parameter to g++ to generate the file as compiler sees it after preprocessing. Very useful to catch these include-related problems.
The first issue derives from your include "mess". When Organism.h is processed (maybe because a corresponding Organism.cc is compiled) the include statement is replaced by the actual contents, i.e. it is replaced by the contents of World.h. That effectively yields a translation unit where the declaration of World stands before the declaration of Organism, hence leading to the error.
You could also probably remove #include "Organism.h" from your World.h as you have included that in both your Ant and Doodlebug classes, and both of those are included in your World class.

c++ how to include (circular dependency)?

I have Environment.h file:
#include <windows.h>
#include "interfaces.h"
#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
class Environment {};
#endif
and i have Interfaces.h file:
#ifndef INTERFACES_H
#define INTERFACES_H
class IMoving {
public:
virtual void Move() = 0;
};
#endif
in interface IMoving i would like to get an Environment class, to know how to move
class IMoving {
public:
virtual void Move(Environment*) = 0;
};
if i want to do this i need to include environment.h
#include "Environment.h"
and here i'm getting an error, becouse Environment.h - includes Interfaces.h and Interfaces.h - includes Environtment.h. So how to make it work ?
Sorry for spelling mistakes
For circular dependencies one can use Forward declaration(s)
In Interfaces.h just above interface definition, forward declare Environment as follows:
class Environment;
Then when you implement IMoving in a class, you will include Environment.h in its implementation (cpp) file.
You can read more about Forward declaration here.
It looks like you misspelled the class name a few times (Environtment,Envrirontment). Could that be the origin of your issue?
Otherwise I typically use the Forwarded Declaration

Error while trying to use class in another class

I'm writing something in C++. I have 2 classes which I want to contain one into the other as in the folowing (these are just the header files):
//Timing.h
#ifndef _Timing_h
#define _Timing_h
#include "Agent.h"
class Timing{
private:
typedef struct Message{
Agent* _agent; //i get here a compilation problem
double _id;
} Message;
typedef struct MessageArr{
} MessageArr;
public:
Timing();
~Timing();
};
#endif
//Agent.h
#ifndef _Agent_h
#define _Agent_h
#include <string>
#include "Timing.h"
using namespace std;
class Agent{
public:
Agent(string agentName);
void SetNextAgent(Agent* nextAgent);
Agent* GetNextAgent();
void SendMessage(Agent* toAgent, double id);
void RecieveMessage(double val);
~Agent();
private:
string _agentName;
double _pID;
double _mID;
Agent* _nextAgent;
};
#endif
The compilation error is in the Timing.h file inside the definition of the struct:
expected ';' before '*' token
What am I doing wrong?
Try not to include "Agent.h" in Timing.h but include a forward reference instead:
#ifndef _Timing_h
#define _Timing_h
class Agent;
class Timing{
private:
typedef struct Message{
Agent* _agent; //I get here a compilation problem
double _id;
}Message;
typedef struct MessageArr{
}MessageArr;
public:
Timing();
~Timing();
};
#endif
You can include Agent.h in the timing.cpp file.
This way you remove the circular reference and you reduce the coupling between the classes.
Since you don't use the class Timing in your class Agent, you can remove this include as well (but this might be a copy mistake from your shortened example).
Basically - whenever you need either the size of an object or some of it's functionality, you must include its header file. If you don't need it (e.g. if you use only pointers to this object or references), you should not. This reduces compile time (especially for large projects)
For the 1 instance problem - check your favorite design patterns book (e.g. the GoF). The singleton pattern might be what you need.
Rule of thumb.
Do not include other header files from your header files if you don't need to.
Pre-Compiled header file stuff being a notable exception.
If your class only depends on a pointer or a reference you do not need the header file:
Use forward declaration in this situation.
In the source file include only the header files you need to make it work
Include them from most specific to least specific.
This will prevent the problem of hiding a dependency.
Other notes:
Do not use Underscore followed by a capitol letter.
This is reserved for the implementation. see
As in #define _Timing_h
Also note it is traditional that macros are all upper case.
Do not put using namespace X; in a header file
If you do this you pollute the namespace for everybody that uses your header file.
This is a real easy way to PO other developers who now have to re-factor their code to make sure it does not use any of a bunch of new classes/functions/templates that are suddenly being resolved against that was not there before.
So try this:
Timing.h
#ifndef TIMING_H
#define TIMING_H
class Agent;
class Timing{
// STUFF
};
#endif
Agent.h
#ifndef AGENT_H
#define AGENT_H
#include <string>
class Agent{
// STUFF
};
#endif
Timing.cpp
#include "Timing.h"
#include "Agent.h"
// STUFF
Agent.h
#include "Agent.h"
using std::string; // Bring as little as possable into the the global namespace.
// prefer to prefix all cases with std::
// STUFF.
You can't have circular includes.
Stop including "Timing.h" from "Agent.h", since it's not needed there.
Also, you don't need to have the "Agent.h" included in "Timing.h" either, just use a forward reference:
class Agent;
This makes it possible to have pointers to something called Agent.
You need to add the forward declaration of Agent in Timing.h
// Timing.h
#ifndef _Timing_h
#define _Timing_h
class Agent; // fwd declaration.
class Timing{
private:
typedef struct Message{
Agent* _agent; // without fwd decln Agent type is unknown here.
// rest all same.
EDIT:
As suggested by others, you should not be including Agent.h in Timing.h