Reputation: 403
I am learning object oriented programming.
To know which object is being destroyed, I want to add some code in the destructor of a class and use an attribute to do it.
For example-
class player{
public:
string name;
int health;
~player(){
cout<<name<<" destroyed";
}
};
In this example, name correctly helps me identify the object which is being destroyed.
But if there weren't any such attributes which could help me know which object was being destroyed, what should be done.
Is there a way to print the object's name itself. ( i.e. if I create a player enemy;
then enemy is what I mean to say by name)
Upvotes: 0
Views: 43
Reputation: 35455
If you want it to be versatile, you can overload operator <<
instead of focusing solely on the destructor and outputting bits and pieces of your class attributes.
Here is an example:
#include <string>
#include <ostream>
#include <iostream>
class player {
std::string name;
int health;
public:
player(const std::string& n, int h) : name(n), health(h) {}
~player() { std::cout << "Destroying the following: " << *this << "\n"; }
friend std::ostream& operator << (std::ostream& os, const player& p);
};
std::ostream& operator << (std::ostream& os, const player& p)
{
os << p.name << " " << p.health;
return os;
}
int main()
{
player p1("Joe", 1);
player p2("Sam", 2);
std::cout << p1 << "\n" << p2 << "\n";
}
Output:
Joe 1
Sam 2
Destroying the following: Sam 2
Destroying the following: Joe 1
You can follow what was done by looking at some documentation here.
Upvotes: 1