Question

I'm struggling to instantiate a class, within another class. My main concern is... Where do I place the constructor? In the header file? In the class file? Or in both? Nothing seems to work right. I'll try to put this as simple as possible. Let me know if it's too simple ;) This is how I would THINK it should be:

GameWorld.h:

#include "GameObject.h"

class GameWorld
{
protected:
    GameObject gameobject;
}

GameWorld.cpp:

#include "GameWorld.h"

void GameWorld::GameWorld()
{
    GameObject gameObject(constrctor parameters);
}

//When I compile the program, the values in the gameObject, are not set to anything.

So that's one of the things I've tried. Putting the constructor in the header, won't work either, for obvious reasons; I can't give it any parameters from GameWorld.

What is the correct way to do this?

Edit: Oops. Removed something useless.

No correct solution

OTHER TIPS

You need to initialize the GameObject member in the containing class' initializer list.

// In the GameWorld.h header..
class GameWorld
{
public:
    GameWorld(); // Declare your default constructor.

protected:
    GameObject gameobject; // No () here.
}

// In the GameWorld.cpp implementation file.
GameWorld::GameWorld() // No 'void' return type here.
  : gameObject(ctorParams) // Initializer list. Constructing gameObject with args
{
}

I believe you would want to declare the GameObject within the GameWorld header, then create the GameObject object in the GameWorld constructor.

//GameWorld.h
#include GameObject.h

class GameWorld
{
private:
    GameObject object;

};

//GameWorld.cpp
#include GameWorld.h

GameWorld::GameWorld()
{
   object();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top