does arrangement matter in this? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

does arrangement matter in this?

hello, why does this code output something which is "yo yo yo" #include <iostream> #include <string> using namespace std; class myClass { private: string name; public: void setName(string x) { name=x; } string getName() { return name; } }; int main() { myClass obj; obj.setName("yo yo yo"); cout << obj.getName(); } and by changing name=x; to x=name; it doesn't output anything???

30th Sep 2020, 10:40 AM
Youssef Hossam
Youssef Hossam - avatar
2 Answers
+ 1
Definitely Matters. In name = x ; here x value assigned to name. It works like : target = source; source => target. In first one, you are passing string into x and assigning to name. Now x, name have values =>"yo yo yo". In next x = name, name is still unassigned no value, and getting assigned to x. And printing name, now see both x, name have none values.
30th Sep 2020, 1:18 PM
Jayakrishna 🇮🇳
+ 1
obj.setName sets the value of name variable to yo yo yo and getName() returns it name=x means assign x value which is yo yo yo to variable name x=name means assign variable name which is unintialized to variable x which is being passed the yo yo as output ,anyway that's totally valid ,the reason you aren't getting output is because you are returning name variable not x
30th Sep 2020, 11:02 AM
Abhay
Abhay - avatar