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?

5th Nov 2016, 3:06 PM
Król Mateusz
Król Mateusz - avatar
8 Antworten
+ 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
5th Nov 2016, 3:17 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
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; }
5th Nov 2016, 3:23 PM
Król Mateusz
Król Mateusz - avatar
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.
5th Nov 2016, 3:27 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
I write this on local and have all files in one folder.
5th Nov 2016, 3:31 PM
Król Mateusz
Król Mateusz - avatar
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
5th Nov 2016, 3:34 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
0
https://scr.hu/N6KpAR this is my main and .hpp of the class
5th Nov 2016, 3:35 PM
Król Mateusz
Król Mateusz - avatar
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
5th Nov 2016, 4:10 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
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.
24th Nov 2016, 4:28 AM
dzmitry