+ 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 RĂ©ponses
+ 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