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.
Yes you definitely can instantiate a class inside a constructor method of another 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.
so by line 1, class is both loaded and initialized and hence there is no problem in instantiating an instance of class in itself.
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#.
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
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With