Question

I am making a game in which my main class for controlling game objects is "inGame". There will be several other custom made classes composed inside "inGame".

like,

class mouse
{
  int x, y;
  bool alive;
  float speed;
  public:
    mouse(int xx, int yy, float spd, bool alv)
    {
        x = xx; y = yy; speed = spd; alive = alv;
    }
    // member functions
};

class inGame
{
  mouse m1; 
  dog d1; // single object which are easy to construct
  public:
    inGame() : d1(200, 400, 1.5, false), m1(40, 40, 0.5, false) //This works fine
    {} //coordinates fixed and set by me
    // member functions
};

But now lets say I want 3 mouses. So i thought of m1[3] or maybe a vector.

class inGame
{
  mouse m1[3]; // like i want 3 mouse(animals) in the game screen
  dog d1; // single object which are easy to construct
  public:
    inGame() : d1(200, 400, 1.5, false) //Confusion here m1(40, 40, 0.5, false)
    {}
    // members
};

so I've tried the following:

inGame() : m1[0](1,2,3,true), m1[1](2,3,4,true), m1[2](3,4,5,true) { } //NO
inGame() : m1 { (1,2,3,true), (2,3,4,true), (3,4,5,true) } { } //NO
inGame() : m1 { (1,2,3,true), (2,3,4,true), (3,4,5,true); } { }

even if I use std::vector m1 then how to I initialize through the inGame default constructor? Would it be writing inside the constructor?

mouse temp(1,2,3,true);
m1.push_back(temp);

Which is the better approach? in main I will just do:

inGame GAME; //Just to construct all animals without user requirement

Thanks.

UPDATE:

no luck with

inGame() : m1 { mouse(1,2,3,true), mouse(2,3,4,true), mouse(3,4,5,true) } { }
inGame() : m1 { {1,2,3,true}, {2,3,4,true}, {3,4,5,true} } { }

There an error after "m1 {" that "expected a )". And m1 { "}<--" that "expected a ;"

Was it helpful?

Solution 2

You need to use brace-enclosed initializers:

inGame() : m1 { {1,2,3,true}, {2,3,4,true}, {3,4,5,true} } { } 

Without C++11, you will need to use a container such as std::vector<mouse> and populate it inside the body of the constructor, or using a function that returns suitably initialized one:

std::vector<mouse> make_mice()
{
  std::vector<mouse> v;
  v.reserve(3);
  v.push_back(mouse(1, 2, 3, true));
  v.push_back(mouse(2, 3, 4, true));
  v.push_back(mouse(3, 4, 5, true));
  return v;
}

then

inGame() : m1(make_mice()) {}

where m1 is now an std::vector<mouse>

OTHER TIPS

Assuming you're using C++11 or later,

inGame() : m1{{1,2,3,true}, {2,3,4,true}, {3,4,5,true}}
{}

This will work whether it's a regular array, std::array, std::vector, or any other sequence container.

If you're stuck with an ancient dialect, then initialisation will be more problematic. Using a vector, and calling push_back in the constructor as you describe, is probably the least nasty approach. To use an array, you'd need to give mouse a default constructor, then reassign each element in the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top