struct AnimationData
{
struct Frame
{
int x1, y1, x2, y2;
float dt; // seconds
Frame() : x1(0), y1(0), x2(1), y2(1), dt(1) {}
} * frames;
int frame_count;
std::string name;
AnimationData(int fc, std::string n) : frame_count(fc), name(n)
{
frames = new Frame[fc];
for (int i = 0; i < fc; i )
{
std::cout << frames[i].x2 << '\n';
}
}
};
int main()
{
AnimationData data{10, "test"};
data.frames[1].x1 = 666;
std::cout << "Start" << '\n';
for (int i = 0; i < data.frame_count; i )
{
std::cout << data.frames[i].x1 << '\n';
}
return 0;
}
This outputs:
1
1
1
1
1
1
1
1
1
1
Start
0
666
0
0
0
0
0
0
0
0
Why Does it turn everything to zero except for the one I set? (Note I know nothing about copy and move constructors idk if they are related to this)
CodePudding user response:
Why Does it turn everything to zero except for the one I set?
Because the default constructor Frame::Frame()
will initialize x1
, y1
to 0
and x2
, y2
, dt
to 1
when you wrote:
frames = new Frame[fc]; //default ctor will initialize x1, y1 to 0 and x2, y2, dt to 1
That is, the 10
Frame
objects that will be allocated on the heap will be created using the default constructor of Frame
which will initialize x1
, y1
to 0
and x2
, y2
and dt
to 1
. This is why when you wrote:
std::cout << frames[i].x2 << '\n'; //prints 1 becasue default ctor initialized `x2` to `1`
the above statement will print 1
as default ctor initialized x2
to 1
For the same reason when you wrote:
std::cout << data.frames[i].x1 << '\n'; //will print 0 as default ctro initialized x1 to 0 except for `data.frames[1].x1` which you set to `666`.
the above statement will print 0
since the default ctor initialized x1
to 0
except for data.frames[1].x1
which you specifically set to 666
.
You can confirm that the default ctor is used by adding a cout statement inside it as done below:
Frame() : x1(0), y1(0), x2(1), y2(1), dt(1) {
std::cout<<"default ctor called"<<std::endl;
}
The output of the modified program is:
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
default ctor called
1
1
1
1
1
1
1
1
1
1
Start
0
666
0
0
0
0
0
0
0
0