Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Instantiating a class, within a class. The correct way?

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.

like image 622
Frederik Avatar asked Mar 06 '14 23:03

Frederik


People also ask

Can you instantiate a class within another class?

Yes you definitely can instantiate a class inside a constructor method of another class.

How do you instantiate the class?

Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The new operator returns a reference to the object it created.

Can you instantiate a class within itself?

so by line 1, class is both loaded and initialized and hence there is no problem in instantiating an instance of class in itself.

What is instantiating a class C#?

When you create a new object in C# for a class using the new keyword, then it is called instantiation. Use the new operator to instantiate a class in C#.


1 Answers

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
{
}
like image 139
Aesthete Avatar answered Sep 28 '22 00:09

Aesthete