I have this code on Visual C++ 2010
#include <iostream>
#include <string>
using namespace std;
class Human {
private:
int magic;
int health;
string name;
public:
int GetMagic() const;
int GetHealth() const;
Human(int, string);
~Human();
};
//helper
int Human::GetHealth() const {
cout <<"This returns Human::health" << endl;
return Human::health;
}
int Human::GetMagic() const {
cout <<"This returns this->magic"<< endl;
return this->magic;
}
//con/destructor
Human::Human(int a, int b, string c): health(a), magic(b), name(c)
{
cout<<c<<" is born!"<<endl;
}
Human::~Human()
{
cout <<this->name << " is killed!" << endl;
}
int main (){
Human lucife(20,10,"Lucife");
cout << lucife.GetHealth()<<endl;
cout << lucife.GetMagic()<<endl;
lucife.~Human();
cout << lucife.GetHealth()<<endl;
cout << lucife.GetMagic()<<endl;
cout<<endl;
lucife.~Human();
system("pause");
}
And when I run it:
Lucife is born!
This returns Human::health;
20
This returns this->magic
10
Lucife is killed!
This returns Human::health
20
This returns this->magic
10
is killed!
I have 3 questions:
- After I killed instance "lucife" the first time, why did the 2 methods GetHealth() and GetMagic() still worked?
- The second time I called ~Human() on instance "lucife", why didn't it print out "Lucife is killed!" like the first time? What exactly happened here? Is the name value deleted?
- Does return Human::health and return this->health mean the same thing? I tried it and see that there is no difference. I think both of them return the health of the instance on which the method was called ("lucife" in this case).
Many thanks to you