Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Initialization of member variables

I have a confusion on class member variable initialization.

Suppose in my .h file is:

class Test {

int int_var_1;
float float_var_2;

public:
       Test();
}

My .cpp would be:

Test::Test() : int_var_1(100), float_var_2(1.5f) {}

Now when I instantiate a class the variables get initialized to 100 and 1.5.

But if that is all I'm doing in my constructor, I can do the following in my .cpp:

int Test::int_var_1 = 100;
float Test::float_var_2 = 1.5f;

I'm confused as to the difference between initializing the variables in constructors or with the resolution operator.

Does this way of initializing variables outside constructor with scope resolution only apply to static variables or is there a way it can be done for normal variables too?

like image 297
madu Avatar asked Aug 29 '12 02:08

madu


People also ask

How do you initialize a member variable?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.

Should member variables be initialized?

You should always initialize native variables, especially if they are class member variables. Class variables, on the other hand, should have a constructor defined that will initialize its state properly, so you do not always have to initialize them.

Are member variables initialized C++?

Member variables are always initialized in the order they are declared in the class definition.

Where are the member variables of a class initialized?

In C++, class variables are initialized in the same order as they appear in the class declaration. Consider the below code. The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.


1 Answers

You cannot substitute one for the other. If the member variables are not static, you have to use the initialization list (or the constructor body, but the initialization list is better suited)*. If the member variables are static, then you must initialize them in the definition with the syntax in the second block.

* Als correctly points out that in C++11 you can also provide an initializer in the declaration for non-static member variables:

class test {
   int data = 5;
};

Will have data(5) implicitly added to any initialization list where data is not explicitly mentioned (including an implicitly defined default constructor)

like image 127
David Rodríguez - dribeas Avatar answered Sep 18 '22 17:09

David Rodríguez - dribeas