can you explain this code pleeease | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

can you explain this code pleeease

#include <iostream> #include <string> using namespace std; class myClass { public: string name; }; int main() { myClass myObj; myObj.name = "SoloLearn"; cout << myObj.name; return 0; } //Outputs "SoloLearn" my doubts are what name,string and #include<string>do? ---- cant I do this #include <iostream> #include <string> using namespace std; class myClass { public: void name (string name) cout<< name; }; int main() { myClass myObj; myObj.name(solo learn); return 0; }

19th Feb 2018, 11:35 AM
Jay Jay
Jay Jay - avatar
2 Answers
+ 3
* string -> It's a variable's data type, an ordered sequence of characters. * name -> It's the name assigned to the variable type string. * #include<string> -> It's a library, you need to include the <string> library to use the string data type. Alternatively, you can use a library that includes the string library, for example, #include <iostream>, so you can remove #include <string> from this code. The second code has some errors: * void name (string name) -> the code of a method has to be enclosed in Curly Bracket {}. * myObj.name(solo learn); -> a string has to be enclosed in double quotation marks. myObj.name("solo learn"); Correct code: #include <iostream> #include <string> using namespace std; class myClass { public: void name (string name){ cout<< name; } }; int main() { myClass myObj; myObj.name("solo learn"); return 0; }
19th Feb 2018, 12:38 PM
J Domingo Jiménez J
J Domingo Jiménez J - avatar
+ 2
If you do not know what class field nor string is, I'd refer you to C++ tutorials is this app.
19th Feb 2018, 12:27 PM
Jakub Stasiak
Jakub Stasiak - avatar