Sunday, 23 April 2017

c++ - Why is my destructor being called and how can I fix it

Hey guys so I'm having 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 
#include
#include
#include

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"<}

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"< cout< --count;
cout<<"Now you have a total number of "<}


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"< cin>>choice;

foo=creature(choice);

if(choice==1)
{
cout<<"hi"< }

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...