0

im new in the C++ world and coding in general, just started studying getters and setters and made areally simple exercise to practice them, the build seems to have 0 errors and 2 minor warnings, however, when I try to use a function to return a private variable and print it, it simply crashes the program, however, if i use the last function I made "getAccount()" It seems to work just fine.

After some poking, it seems like the problem is with the getter functions, just calling them crashes the program, here's the code:

main.cpp

#include <iostream>
#include "Person.h"
using namespace std;

int main()
{
    User user;
    user.setUser("someuser");
    user.setPassw("somepassword");

    cout << user.getPassw() << endl;
    cout << user.getUser() << endl;

    user.getAccount();
}

Person.h

#define PERSON_H
#include <iostream>

using namespace std;

class User
{
   private:
        string username;
        string password;
    public:
        string setUser(string usernm);
        string setPassw(string pass);
        string getUser();
        string getPassw();
        void getAccount();


};

#endif // PERSON_H

Person.cpp

#include <iostream>
#include "Person.h"

using namespace std;

string User::setUser(string usernm){
    usernm = username;
}

string User::setPassw(string pass){
    pass = password;
}

string User::getUser(){
    return username;
}

string User::getPassw(){
    return password;
}

void User::getAccount(){
    cout << "Account is:" << endl;
    cout << "Username: " + username << endl;
    cout << "Password: " + password << endl;
}
Enzen
  • 3
  • 1

1 Answers1

3

Not all functions declared to return values actually return values so you have Undefined Behaviour and anything could happen.

Example:

string User::setUser(string usernm){
    usernm = username;
    // should return a string here
}

string User::setPassw(string pass){
    pass = password;
    // should return a string here
}

Apart from that, you assign usernm and pass when you should assign username and password so the set operations does not set the member variables.

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • 3
    nice catch, I checked the getters but missed the setters – 463035818_is_not_an_ai May 25 '20 at 08:42
  • 3
    I missed this, I guess the '2 minor warnings` are about exactly this issue. Never ignore warnings! – john May 25 '20 at 08:42
  • Thank you! I managed to solve the issue after adding the return values to those functions, it seems I really need to study the basics of functions and the return statement again. – Enzen May 25 '20 at 13:34
  • @Enzen You are welcome. If you don't want the functions to return anything, declare them `void`, like: `void setUser(string usernm);` Such a function does not return a value. – Ted Lyngmo May 25 '20 at 13:36
  • 1
    After changing the functions to void the program works as intended, thanks! – Enzen May 25 '20 at 14:04