-2

No errors are generated, but nothing is printed when I run the code. Help?

class NatalieClass{
  public: 
    void setName(string x){
      x = name;
    }

    string getName(){
      return name;
    }

  private:
    string name;
};

int main(){
  NatalieClass ob1;
  ob1.setName("Hello World");
  cout << ob1.getName();
  return 0;
} 

The function is supposed to print "Hello World" but instead nothing is printed.

dedObed
  • 1,313
  • 1
  • 11
  • 19
natalie
  • 9
  • 1

1 Answers1

0

In setName:

void setName(string x){
  x = name;
}

You are setting the argument you get passed (which is "Hello World" in this example) to the member variable x, which is an empty string. Then you print out name, which is still an empty string, so it'll look like you print out nothing.

You probably meant to assign name to x instead of the other way around:

void setName(string x) {
  name = x;
}

Side note : seeing your code snippet I'm assuming you have using namespace std; somewhere at the top, this is considered bad practice, use std:: instead..

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122