Creating game objects with a class?

Started by
3 comments, last by Dante12129 10 years, 4 months ago

Hello, i've just recently hit a big wall with my game programming.

I've been trying to make a class that can create any kind of game object, but it needs to use the header files for other objects in order to work.

Sure, doesn't sound like much of a problem but... what if I want the Player to use the object creator class to create more objects?

As you can see, i've run into a circular dependancy problem. Does anyone have a solution to this? Or is my method just conveluted?

View my game dev blog here!

Advertisement

[source]

//factory.h

#pragma once

class GameObject;

class SomeFactory()

{

public:

GameObject *CreateGameObject();

}

//factory.cpp

#include "GameObject.h"

GameObject *SomeFactory::CreateGameObject(){return new GameObject();}

[/source]

Easy as that to fix circular references.

Cheers!

Just to elaborate a little more on kauna's solution:


#pragma once
//stuff

The above code is equivalent to header guards, as seen in the following code. It is used to make sure things are only declared exactly once. Examples of when they are needed are circular inclusion and polymorphism.


#ifndef __FACTORY_H__
#define __FACTORY_H__
// stuff
#endif // __FACTORY_H__

In the case of circular inclusion, it is often possible to omit including the header of the other class and simply use a forward declaration, as seen here:


class GameObject; // instead of "#include <GameObject.h>
"I would try to find halo source code by bungie best fps engine ever created, u see why call of duty loses speed due to its detail." -- GettingNifty

Just to elaborate a little more on kauna's solution:


#pragma once
//stuff

The above code is equivalent to header guards, as seen in the following code. It is used to make sure things are only declared exactly once. Examples of when they are needed are circular inclusion and polymorphism.


#ifndef __FACTORY_H__
#define __FACTORY_H__
// stuff
#endif // __FACTORY_H__

In the case of circular inclusion, it is often possible to omit including the header of the other class and simply use a forward declaration, as seen here:


class GameObject; // instead of "#include <GameObject.h>

But dont Forward declarations prevent you from accessing methods and variables from the objects? If i want to create a new player with the object creator, and a new bullet with the player, how do I access the methods?

View my game dev blog here!

Look at the source file, it includes GameObject.h. The header only uses a pointer to GameObject, so it doesn't actually need to know about it. The source file is what is actually using it, hence why you include it there. Since pointers and references are known sizes, the compiler can use them without full definitions of types.

Also, why is your factory method in a class when it could just be a free function in this case?

This topic is closed to new replies.

Advertisement