Is this object destroyed?

A

Anon Email

In the code below, when the member function AddInput is called, a new
object aNum is created, of type InputNum. Actually, AddInput is called
twice, thus creating two separate aNum objects. I gather that after
AddInput is executed, each separate aNum object is destroyed? Is no
destructor required?

Cheers,

Deets


#include <iostream>
using std::cout;
using std::cin;
using std::endl;

class InputNum
{
public:
InputNum (char msg [])
{
cout << msg;
cin >> _num;
}

int GetValue () const { return _num; }

void AddInput (char msg [])
{
InputNum aNum (msg);
_num = GetValue () + aNum.GetValue ();
cout << aNum.GetValue ();
}


private:
int _num;
};

char SumString[] = "The sum is ";

int main()
{
InputNum num ("Enter number ");
num.AddInput ("Another one ");
num.AddInput ("One more ");
cout << SumString << num.GetValue () << endl;
}
 
M

Moonlit

Anon Email said:
In the code below, when the member function AddInput is called, a new
object aNum is created, of type InputNum. Actually, AddInput is called
twice, thus creating two separate aNum objects. I gather that after
AddInput is executed, each separate aNum object is destroyed? Is no
destructor required?
Correct. It is created on the stack. On returning from the subroutine the
destructor for aNum is called. Since nothing special is done the default
constructor suffice

So nothing has to be done.

Regards, Ron AF Greve.
Cheers,

Deets


#include <iostream>
using std::cout;
using std::cin;
using std::endl;

class InputNum
{
public:
InputNum (char msg [])
{
cout << msg;
cin >> _num;
}

int GetValue () const { return _num; }

void AddInput (char msg [])
{
InputNum aNum (msg);
_num = GetValue () + aNum.GetValue ();
cout << aNum.GetValue ();
}


private:
int _num;
};

char SumString[] = "The sum is ";

int main()
{
InputNum num ("Enter number ");
num.AddInput ("Another one ");
num.AddInput ("One more ");
cout << SumString << num.GetValue () << endl;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top