I'm trying to make a Monster
generator using vectors and classes to allow the user to create and delete Monster
objects as they wish. However, when I call the constructor of Monster
in my code it also immediately triggers a destructor, thereby removing Monster
from the the vector container.
This is the fragment of my code, which creates and destroys the Monster
object:
while (p == 't')
{
cout << "Generate (g) or remove (u) a monster?" << endl;
cin >> p;
while (p == 'u' && Monster::n == 0)
{
cout << "No monsters to remove." << endl;
cout << "Generate (g) or remove (u) a monster?" << endl;
cin >> p;
}
while (p != 'g' && p != 'u')
{
cout << "Error. Follow the instructions." << endl;
cout << "Generate (g) or remove (u) a monster?" << endl;
cin >> p;
}
if (p == 'g')
{
{
vec.push_back(Monster());
vec[Monster::n].print();
}
}
if (p == 'u')
{
vec.~Monster();
}
cout << "Continue (t) or finish (n)?" << endl;
cin >> p;
while (p != 't' && p != 'n')
{
cout << "Error. Follow the instructions?" << endl;
cout << "Continue (t) or finish (n)?" << endl;
cin >> p;
}
This is the constructor for Monster
:
Monster::Monster()
{
ostringstream buffer;
buffer << Monster::n;
string name = buffer.str();
Monster::setname(name);
Monster::settype(MonsterType(rand() % 7 + 1));
Monster::setattack(rand() % 25);
Monster::sethealth(rand() % 15);
cout << endl << "Monster generated." << endl << endl;
Monster::n++;
}
This is the destructor:
Monster::~Monster()
{
cout << "Monster removed." << endl << endl;
Monster::n--;
}
When I input the character 'g'
, it creates a Monster
object as expected but then immediately destroys it, even before its stats are printed with the print()
method. This means my code is not acting as expected, as it will never allow the proper creation or destruction of Monster
objects.
Can someone please help me understand what's going on here?
EDIT:
Alright, I was able to somewhat solve the issue by making another constructor.
This is it:
Monster::Monster(const Monster & mon)
{
Monster::name = mon.name;
Monster::type = mon.type;
Monster::attack = mon.attack;
Monster::health = mon.health;
cout << endl << "Monster created (cpy)." << endl << endl;
Monster::n++;
}
I edited the point where the user decides to generate a Monster
to the following:
{
vec.push_back(Monster());
vector<Monster> veccpy = {};
veccpy.push_back(Monster(vec[Monster::n-1]));
vec.back().print();
}
When I lauch the program, it spits out something like this:
Monster created
Monster created (cpy)
Monster removed
Monster created (cpy)
Monster created (cpy)
Monster removed
Monster's stats
Now, the odd thing is even though it uses those constructors so oddly, the program works as I intended it to. n
iterates as it should, I can remove or add Monster
as I intended and the Monster
stats are displayed as they should.
Could someone point to what I'm doing wrong here?