By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,255 Members | 2,640 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,255 IT Pros & Developers. It's quick & easy.

I learnt the following program online but when I run the program the output is blank

P: 3
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class dev{
  6.  
  7.     public:
  8.         void setName(string x){
  9.             x = name;
  10.         }
  11.  
  12.         string getName(){
  13.             return name ;
  14.         }
  15.     private:
  16.         string name;
  17.  
  18. };
  19.  
  20. int main()
  21. {
  22.     dev dg;
  23.     dg.setName("Devansh Garg");
  24.  
  25.     cout << dg.getName();
  26.  
  27.     return 0;
  28. }
  29.  
When I run this program it displays a blank output

PLEASE HELP
Jun 1 '17 #1

✓ answered by weaknessforcats

name is in your object.

x = name assigns the name in your object to the calling parameter of the function. This is backwards from what you want.

name = x assigns the name passed in the function to the name in your object. This is what you want.

Share this Question
Share on Google+
4 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
Check this:
Expand|Select|Wrap|Line Numbers
  1. public:
  2.     void setName(string x){
  3.         x = name;
  4.     }
This is the member function to set the name. As you can see, it is the x calling parameter that is set and not the name.
Jun 1 '17 #2

P: 3
Not understood the difference between the two
Jun 1 '17 #3

P: 3
But I wrote x = name; then the value passed to x should be equal to name
Jun 1 '17 #4

weaknessforcats
Expert Mod 5K+
P: 9,197
name is in your object.

x = name assigns the name in your object to the calling parameter of the function. This is backwards from what you want.

name = x assigns the name passed in the function to the name in your object. This is what you want.
Jun 1 '17 #5

Post your reply

Sign in to post your reply or Sign up for a free account.