+ 2
Help with a C++ constructor
Hi all, Can anyone help me understand how this constructor work? I didn't see this structures until now. MyClass::MyClass() : myVar1(MYCONSTANT1), myVar2(MYCONSTANT2){ } I think it attibutes the constant values to the variables. Am I correct? So the equivalent would be as below? MyClass::MyClass(){ myVar1 = MYCONSTANT1; myVar2 = MYCONSTANT2; }
1 Resposta
+ 4
yes you are correct. they do not have to be constants though. both methods assign values to member variables.
I usually use the first method you listed when all the values are known at the time of the objects creation.
I use the second method when the values need to be modified in some way or new objects are required for the classes initialisation.