Green Shard
Green Shard

Reputation: 13

Unable to save to variable in Class?

Beginner code. Compiles fine. SetMemo seems to work (as it repeats the input) but when I try to use ReadMemo, savedmemo seems to be NULL. Anything else included in the line will print, except that. What am I doing wrong? Am I accidentaly wiping the variable elsewhere?

#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int firstboot = 1;

class MEMOCLASS {
    public:
    void SetMemo(string memoinput_pvt) {
        savedmemo = memoinput_pvt;
        cout << savedmemo << " saved as a memo!" << endl;
        };
    string ReadMemo(){
        return savedmemo;
    };
    private:
    string savedmemo;
};

int main()
{
    MEMOCLASS MMObj;
    string input;
    string memoinputmain;
    if (firstboot == 1) {
        cout << "Hello! Please use \"write memo\" to store a memo or \"read memo\" to read a previously stored memo. Type \"exit\" to quit the programme." << endl;
        firstboot = 0;
    }
    else {
        cout << "Ok, anything else I can do for you?" << endl;
    }
    getline(cin, input);
    if (input == "write memo") {
        cout << "Ok, go ahead. Press Enter to record the Memo.\n";
        getline(cin, memoinputmain);
        MMObj.SetMemo(memoinputmain);
        main();
    }
    else if (input == "read memo") {
    cout << "The memo reads: " << MMObj.ReadMemo() << endl;
    main();
    }
    else if (input == "exit")
    {
        cout << "Cya!\n";
        return 0;

    }
    else if (input == "help")
    {
        cout << "Use \"write memo\" to store a memo or \"read memo\" to read a previously stored memo. Type \"exit\" to quit the programme.\n";
        main();
    }
    else {
        cout << "Invalid input!\n";
        main();
    }
}

Upvotes: 1

Views: 109

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409176

Two problems:

  1. In C++ you're not allowed to call the main function recursively. Use loops instead. (Calling main in any way, no matter from where, in your code is formally undefined behavior.)

  2. Because you call main recursively, each call results in a new and distinct variable MMObj being created.

Upvotes: 6

doctorlove
doctorlove

Reputation: 19242

First, a point to bear in mind. You shouldn't call main.

Now, when you do call main, the object you create ceases to exist. Any code like

void foo()
{
    int x = 6;
    if (x == 6)
    {
        x = 7;
    }
    foo();
}

will make a new x when it gets called again, giving x with the value 6.

You can pass in your objects to keep them around.

void foo(int x)
{
    if (x == 6)
    {
        x = 7;
    }
    foo(x);
}

In your case, make a new function, e.g. runMMObj

MEMOCLASS runMMObj(MEMOCLASS MMObj) //you know this is a copy, right?
{
    //do reads and writes here
    return MMObj;
}

int main()
{
    MEMOCLASS MMObj;
    MMObj = runMMObj(MMObj);
    //rerun your new function if you want
}

Upvotes: 1

Related Questions