Sunday, 17 September 2017
c++ - Why is my destructor being called and how can I fix it
Answer
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"< }
}
casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV
In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...
-
I'm using Simple HTML DOM to extract data from a HTML document, and I have a couple of issues that I need some help with. On the line th...
-
I've just started to learn CodeIgniter and gotten trouble with example below: My Controller: class Site extends CI_Controller ...
-
I am working with OpenSSL to try and get the SHA512 Hash function to work. When I am writing the code, Visual Studio's intellisense find...
No comments:
Post a Comment