Question

I had a do loop in my program and I needed to reset the values (from constructor) each time the loop happens until the user exits the program. My Question was: How to make a function to reset values (een, old) as each time loop happens?

I have provided the answer below and with the explanation at the end of the page by answering my own question.

class NNew
{
private: 
    int een, old;
public:
    NNew(int nn,int oo)
    {
        een = nn;
        old = oo;
    }
    void newer(int n)
    {
        een = n;
    }
    void Older(int o)
    {
        old = o;
    }
    void reset()
    {
        een = 0;
        old = 0;
    }
};
int main()
{
    char answer1, answer2;
    int n,o;
    NNew *object = new NNew(10,100)
    do
    {
        cout << "Would you like to continue?" << endl;
        cin >> answer1
        if (answer = 'yes')
        {
            do
            {
                (program asks user for inputs for n and o...)
            } while(answer2 !='q');
        }
        object->reset();
    } while(answer1 !='no');
    delete object;
    object = 0;
    return 0;
}
Was it helpful?

Solution 2

The way you have, a new NNew object is create with every iteration of the loop, if you want to keep the same object with every iteration you can try creating the NNew object before the do...while loop.

FYI whenever you create an object on the heap i.e. with the new keyword, you should delete it when you're done with it.

OTHER TIPS

If you want a fresh object on each iteration of the loop, you can just use an automatic variable and let the language deal with constructing and destructing it, instead of worrying about manually resetting it:

do
{
    NNew object(10,100);

    ...
} while (...);

Or if it must be on the heap:

do
{
    NNew* object = new NNew(10,100);

    ...

    delete object;
} while (...);

Thanks for everyone that contributed to find the solution.

My question has the answer in itself. I found out the main reason that my code wasn't working was because of some basic issues outside of the example code.

The example code that I have provided in the question actually works and you can reset constructor values with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top