Reputation: 2470
class A
{
int a = 100;
};
and
class A
{
int a;
public :
A()
{
a = 100;
}
};
I know that there are two approaches because static variables are initialised outside the class and cant that cant be done inside the class. But what difference does it make if i initialise the variable a ( a normal int ) using the constructor or during the declaration itself.
Upvotes: 2
Views: 130
Reputation: 11012
In the following constructor:
class A { int a = 100; };
int a = 100;
is a default member initializer. Non-static data members are initialized in order of declaration in the class definition before entering the constructor.
If you assign a value in the constructor then the variable has already been initialized (as a POD, in this case it was initialized to an indeterminate value) by the time the value is assigned:
A() { a = 100; }
So the difference in this case is that when the constructor is entered in the second example the value of a
is indeterminate whereas in the first it was initialized.
A third way this could have been done is with a member initializer list:
A() : a{100}
{
}
In this case the member initializer (if any) will be ignored, however the sequence of initialization would still be determined by the order of declaration in the class.
As with the first example, the value will be initialized to 100
before starting the constructor.
Upvotes: 0
Reputation: 3671
As per the CPP Core Guidelines: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-in-class-initializer
C.48: Prefer in-class initializers to member initializers in constructors for constant initializers
Reason Makes it explicit that the same value is expected to be used in all constructors. Avoids repetition. Avoids maintenance problems. It leads to the shortest and most efficient code.
In your exact example, the difference isn't such a big deal. But as classes become more complex, and you add children classes and multiple constructors, being able to define the default value in one place simplifies code.
Upvotes: 4