When I run code that attempts to initialize an array of objects, and one has an invalid value, it doesn't seem to call the constructor, which would set a proper default value. The code below produces the output:
1
2
1528112104
Toy code:
#include <iostream>
using namespace std;
class BeeBoop
{
public:
static const int MIN_X = 1;
static const int MAX_X = 2;
BeeBoop(int x);
int getX() { return x; }
bool setX(int x);
private:
int x;
};
int main()
{
BeeBoop boops[] =
{
BeeBoop(1),
BeeBoop(2),
BeeBoop(3)
};
for (int i = 0; i < 3; i++)
cout << boops[i].getX() << endl;
}
BeeBoop::BeeBoop (int x)
{
if(!setX(x))
x = MIN_X;
}
bool BeeBoop::setX(int x)
{
if (x < MIN_X || x > MAX_X)
return false;
this->x = x;
return true;
}
Why isn't it calling the constructor and setting it to the default for BeeBoop(3)?
Even weirder, if I switch the order of the initialization list to
...
BeeBoop boops[] =
{
BeeBoop(1),
BeeBoop(3),
BeeBoop(2)
)
...
The output becomes:
1
0
2
So it initializes to 0, which is also not the default.
this->x, but onlyx, and thereforethis->xis never initialized. Can you confirm?if(!setX(x))behaves differently depending on the value ofx, which has not been initialized. So technically it can any value. If your lucky it's0, in which case your code works, but that doesn't have to be.