In the following code, I create 4 objects named p1
, p2
, p3
, and copy
, of the player
class and I print their attributes using a while
loop, for which the code and the output are the following. But I was expecting a different output and I do not know where I did a copy of the objects in the first 3 cases.
#include <iostream>
using namespace std;
class player{
public:
int xp;
string name;
int health;
player():player(0,0,"none") {}
player(int a):player(a,0,"none") {}
player (int a, int b, string c):name{c},xp{a},health{b} {}
player (player &source)
{
name="copied player";
xp=-1;
health=-1;
}
};
int main()
{
player p1;
player p2(2);
player p3(2,5,"play3");
player copy{p2};
player arr[4]{p1,p2,p3,copy};
int t=4;
while(t--)
{
cout<<arr[3-t].name<<endl;
cout<<arr[3-t].xp<<endl;
cout<<arr[3-t].health<<endl;
}
}
For which I get the following output:
copied player
-1
-1
copied player
-1
-1
copied player
-1
-1
copied player
-1
-1
However, I was expecting:
none
0
0
none
2
0
play3
2
5
copied player
-1
-1
What do I not know?