about private and public in a class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

about private and public in a class

#include <iostream> using namespace std; class myClass { public: void setName(string name) { } string getName() { return name; } private: string name; }; int main() { myClass myObj; myObj.setName("why"); cout << myObj.getName(); return 0; } /*why there is no output for the code above. What will happen if i set a function(setName) with no details and declare the private member "name"in its parameter. Sorry for my poor ebglish*/

26th Sep 2019, 4:42 AM
汝風留名
汝風留名 - avatar
4 Answers
+ 3
The definition of access specifiers is also available in the C++ tutorial.
26th Sep 2019, 6:23 AM
Sonic
Sonic - avatar
+ 1
Because the `setName` method is not changing the value of `name` member (a private variable). When you output the return value of `getName` method, it returned an empty string. Add to `setName` method: // modify value of private variable `name` this->name = name; Or you can also use constructor initializer, so that you can assign a name at object initialization. Hth, cmiiw (Edited)
26th Sep 2019, 5:09 AM
Ipang
0
Thx~
26th Sep 2019, 5:56 AM
汝風留名
汝風留名 - avatar
0
You're welcome
26th Sep 2019, 6:00 AM
Ipang