How Do I assign a variable in a class by using = operator (like we do with int, string and the other data types) ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How Do I assign a variable in a class by using = operator (like we do with int, string and the other data types) ?

As I said in the title above, how can I do it ?

7th Aug 2018, 10:01 AM
Mustafa K.
Mustafa K. - avatar
3 Answers
+ 1
I just want to initialize a variable which is inside the class. f.e class Klass{ int x; } main(){ Klass ks = 5; } and this is gonna set the x variable to 5. I want something like that
7th Aug 2018, 10:26 AM
Mustafa K.
Mustafa K. - avatar
+ 1
So, you want something like this: #include <iostream> using namespace std; class Klass{ public: int value; }; int main() { Klass k; k.value = 5; cout << "Value: " << k.value << endl; return 0; } Observe that your class do not have any constructor, but the default one is still there. In addition, to dirctly access a variable inside an object you need such variable to be public. Last, in main() you need to first instantiate your object and after that you can access its members. That is it.
7th Aug 2018, 11:48 AM
Mark
0
Hi Mustafa, I did not understood your question very well. Do you want to initialize a variable that you declared inside a class using operator =? Or do you want to initialize the entire class object with operator =? Could you explain better what you want?
7th Aug 2018, 10:14 AM
Mark