Your program is creating two objects.
- using x
- using "Player(40);" inside constructor
Sample:
#include <iostream>
using namespace std;
class Player
{
int health;
public:
Player(int pHealth)
{
cout << "One argument constructor this: " << this << "\n";
health=pHealth;
}
virtual ~Player()
{
cout << "destructor this: " << this << "\n";
}
Player()
{
cout << "Default constructor this: " << this << "\n";
Player(40); // Create new object using one argument constructor.
}
void check()
{
cout << "health: " << health << " this: " << this << "\n";
}
};
int main(int argc, char const *argv[])
{
Player x;
x.check();
return 0;
}
Output:
$ g++ -g -Wall 73596563.cpp -o ./a.out
$ ./a.out
Default constructor this: 0xffffcc10
One argument constructor this: 0xffffcbd0
destructor this: 0xffffcbd0
health: -13184 this: 0xffffcc10
destructor this: 0xffffcc10
Hence 0xffffcbd0 being created inside that default constructor.
Hence updated your code same using:
Player():health(40)
{
cout << "Default constructor this: " << this << "\n";
// Player(40); // Create new object using one argument constructor.
}
Output obtained after above update:
$ ./a.out
Default constructor this: 0xffffcc10
health: 40 this: 0xffffcc10
destructor this: 0xffffcc10
Few more comment:
Player x;
x.check();
// Call constructor without creating object.
Player();
Player(2003);
Hence related output:
$ ./a.out
Default constructor this: 0xffffcbf0
health: 40 this: 0xffffcbf0
Default constructor this: 0xffffcc00
destructor this: 0xffffcc00
One argument constructor this: 0xffffcc10
destructor this: 0xffffcc10
destructor this: 0xffffcbf0