Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my destructor being called and how can I fix it [duplicate]

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
    }

}
like image 811
Brogrammer93 Avatar asked Dec 10 '22 23:12

Brogrammer93


1 Answers

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);
like image 124
juanchopanza Avatar answered Jun 09 '23 22:06

juanchopanza