I have issues with my destructor in my c++ program.When I run the program and take the users input, it suddenly calls the destructor before the cout can even print inside the statement. Assume that the user input will be one because I designed this part of the code to only take in the input 1. I thought the destructor gets called when you leave the scope so I was thinking that the destructor should be called atleast after the cout in the if statement which I will comment below to make it easier for you guys to read. If someone can explain my mistake and correct it that would be great! In my headerfile I have
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
class creature{
public:
creature();//default constructor
creature(int a);
~creature();//desconstructor
string getName();//accessor for the name
static int getNumObjects();
private:
string name;
int happy_level;
static int count;
};
In my implementation file I have
#include "creature.h"
int creature::count=0;//initialize static member variable
creature::creature(){//default constructor
name="bob";
++numberobject;
cout<<"The default constructor is being called"<<endl;
}
creature::creature(int a)
{
if(a==1)
{
name="billybob";
}
else if(a==2)
{
name="bobbilly";
}
else if(a==3)
{
name="bobbertyo";
happy_level=1;
}
}
creature::~creature()
{
cout<<"The destructor is now being called"<<endl;
cout<<creature::getName()<<" is destroyed."<<endl;
--count;
cout<<"Now you have a total number of "<<creature::getNumObjects()<<" creature"<<endl;
}
and in my main class I have
#include "creature.h"
int main()
{
creature foo;//this is where the default constructor gets called which is good
int choice;
cout<<"enter 1 2 or 3 to choose ur monster"<<endl;
cin>>choice;
foo=creature(choice);
if(choice==1)
{
cout<<"hi"<<endl;//the destructor gets called before hi is printed out and I don't know why thats happening
}
}
When you do this
foo=creature(choice);
a temporary creature
object is created on the RHS of the assignment. Its destructor is called once the statement is done, i.e. at end of the line.
There isn't really anything to fix, but you can initialize foo
after reading in choice
, rather than default initializing and then assigning:
int choice;
cout<<"enter 1 2 or 3 to choose ur monster"<<endl;
cin>>choice;
creature foo(choice);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With