When iam trying to make a class with an attribute string, it work like this: string name = " "; not like that: string name; why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

When iam trying to make a class with an attribute string, it work like this: string name = " "; not like that: string name; why?

#include <iostream> #include <string> using namespace std; class myClass { public: string name; //doesnt work for me like this. }; int main() { myClass myObj; myObj.name = "SoloLearn"; cout << myObj.name; return 0; }

25th May 2020, 3:29 PM
Abdallah Nagy
Abdallah Nagy - avatar
38 Answers
+ 2
Abdalla Mohamed ooo, ok it is no problem. create constructor in class and initialize member variable. public: MyClass::MyClass(){name =“”;}
25th May 2020, 6:51 PM
george
george - avatar
+ 2
Abdalla Mohamed i was update my code with constructor. take it and check on your syatem
25th May 2020, 6:52 PM
george
george - avatar
+ 1
... i try wait a minute!
25th May 2020, 4:02 PM
george
george - avatar
25th May 2020, 4:06 PM
george
george - avatar
+ 1
Abdalla Mohamed are you check it?! Problem was in constructor?!
25th May 2020, 8:46 PM
george
george - avatar
+ 1
It is strange((
25th May 2020, 9:42 PM
george
george - avatar
+ 1
I'm guessing your getting a null reference error.... If so it is because you cannot use something that is nothing (i.e. null) The compiler needs it to be something. "" is giving it a default of empty string which is something.
26th May 2020, 1:08 AM
Mike Edmison
Mike Edmison - avatar
+ 1
Yes i got it, thank you.
26th May 2020, 1:53 AM
Abdallah Nagy
Abdallah Nagy - avatar
+ 1
I got the PROBLEM YOU CAN just USE " char " in place of " string "!!!
26th May 2020, 5:05 PM
SKALVANOV
SKALVANOV - avatar
+ 1
Yeah
26th May 2020, 9:10 PM
Cedric Etheridge
Cedric Etheridge - avatar
0
?? Worked fine for me in code::blocks.
25th May 2020, 3:54 PM
rodwynnejones
rodwynnejones - avatar
0
Iam using code blocks too and i know the code is working for you but it doesnt work for me. So I've got this error. Error: myClass::name should be initialized in the member initialization list [-werror=effc++]
25th May 2020, 4:34 PM
Abdallah Nagy
Abdallah Nagy - avatar
0
yah thank you very much
25th May 2020, 8:26 PM
Abdallah Nagy
Abdallah Nagy - avatar
0
Actually its not working too :(
25th May 2020, 9:35 PM
Abdallah Nagy
Abdallah Nagy - avatar
0
I dont know whats going on
25th May 2020, 9:35 PM
Abdallah Nagy
Abdallah Nagy - avatar
0
The same error
25th May 2020, 9:36 PM
Abdallah Nagy
Abdallah Nagy - avatar
0
Yup i think the problem in my console. But how , idont know
25th May 2020, 9:43 PM
Abdallah Nagy
Abdallah Nagy - avatar
0
Thank you anyway for your time :)
25th May 2020, 9:48 PM
Abdallah Nagy
Abdallah Nagy - avatar
0
Hello
26th May 2020, 7:53 PM
Cedric Etheridge
Cedric Etheridge - avatar
0
Me too
26th May 2020, 7:54 PM
Cedric Etheridge
Cedric Etheridge - avatar