Member initialization list

Hi.
I understand that when we have constant variables we have to use member initializers to initialize those constant variables.

But my question is why should we still use member initialization lists when we don't have constant variables?

check these two codes:
which one is preferable and why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 #include <iostream>
#include <string>
using namespace std;

class MyClass{
public:
MyClass(int a, int b)
	

	{
	
	var = a;      
	var2= b;

}

	
}
private:
	
	int var;
	 int var2;
	
};

int main()
{
MyClass obj(1,2);

    return 0;
}


and this one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include <iostream>
#include <string>
using namespace std;

class MyClass{
public:
MyClass(int a, int b)
	: var(a), var2(b)

	{
	

}

	
}
private:
	
	int var;
	 int var2;
	
};

int main()
{
MyClass obj(1,2);

    return 0;
}
Last edited on
Always use the initializer list when you can.
This article goes over it pretty well, I agree with what it says:
https://www.geeksforgeeks.org/when-do-we-use-initializer-list-in-c/

For the ints in your example, it doesn't really matter much. But when you don't use the initializer list, objects are default constructed. If you have a member variable that has a costly default constructor, it could save some processes to just call the appropriate constructor.

Reference member variables must be initialized using the initializer list -- you can't have a reference that isn't referencing anything.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Example program
#include <iostream>
#include <string>

class Foo {
    
  public:
    Foo(int& a)
    //: a(a) // error when commented out
    {}
    
    int& a;  
};

int main()
{
  int b = 3;
  Foo f(b);
}


If a class doesn't have a default constructor, you must call the appropriate constructor in the initializater list.

Because a base class is constructed before the child class, if you want non-default base-class construction, you must call the base class in the initializer list.
Last edited on
That article was really helpful, thank you!
Last edited on
Initializing member variables the old fashioned way works most of the time, but in some cases an initialization list must be used.

Since the initialization list works even if not needed, it might just be better to use it all the time as habit. It is faster to type anyways.
Topic archived. No new replies allowed.