+ 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; }

18th Jan 2017, 2:35 AM
Kleber Leal
Kleber Leal - avatar
1 Answer
+ 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.
18th Jan 2017, 2:58 AM
jay
jay - avatar