0
Destructor initializing immediately after constructor.
When I'm calling constructor of my class it runs through the constructor and then immediately do destructor instruction. What's the problem?
8 Réponses
+ 1
Probably, your program is terminated after you call the class and thats why destrutor call it self at the end. try to put some other code or write your name after calling your class. It will make a change, if it not please show your code
0
Doesn't change anything. Same problem. My class:
#include "Monsters.hpp"
#include <iostream>
#include <cstdlib>
using namespace std;
Monsters::Monsters(int id)
{
switch(id) {
case 1:
name = "Rat";
hp = 10;
attack = 1 + rand() % 4;
break;
case 2:
name = "Wolf";
hp =28;
attack = 5+rand() % 10;
break;
}
}
Monsters::~Monsters()
{
cout << "You've killed " << name << endl;
}
0
Can I ask you from where you have include Monsters.hpp file, I mean you are using codeplay ground of this app or you have write it in your local computer.
0
I write this on local and have all files in one folder.
0
can you show code where you implement your code , I mean main function from where you call your class. Your class have no problem
0
https://scr.hu/N6KpAR this is my main and .hpp of the class
0
you create a object in monsters as wolf and than cout its name. program ends immediately it call constructor and than destrutor. Please put some thing like
Monsters wolf;
cout << wolf.name <<endl;
cout << "your name or anything" << endl;
it will output as
constructor
Wolf
your name or anything
destrutor
0
@Aditya kumar pandey
Thanks. Same problem. It didnt seem obvious that in destructor-testing program there was only one operator and resulted in immediate destructor after constructor running.