This is ot correct:
With an int in a normal C++ program, you can assign a value to the int by doing:
Code: ( text )
int a(5);
The second one is just another way to assign values to private variables in a class. Same way as mentioned above
They are the same, just different syntax
When you use a constructor initializer list, the values are placed in the data members as they are created. When you assign values to members inside the constructor, you are changing the value of a data member that already exists.
If your class has a const member:
-
class MyClass
-
{
-
private:
-
const int MAX;
-
public:
-
MyClass();
-
};
-
the value of the MAX member must be placed in the member when it is created. Becuse of this, the code below will produce an error:
-
MyClass::MyClass()
-
{
-
MAX = 10; //ERROR. Cannot change a constant.
-
}
-
There will also be another error about creating a const without a value.
The way around this is the initializer list:
-
MyClass::MyClass() : MAX(10)
-
{
-
}
-
Now the value 10 is used to initialize the MAX member when the MAX member is created.
You will also need the initializer list to call constructors for any base classes, or construtors for any contained class members.
Lastly, this is bad form:
This code is equivalent to:
-
int a = static_cast<int> (5);
-
This form of initialization is in C++ for template writers.