Having a hard time understanding Member Initializers

So I watched this video about Member Initializers:

http://www.youtube.com/watch?feature=player_embedded&v=53VYYMy-LBo#!

And I didn't understand any of it. I've watched all the videos he made about c++ before this one, but for some reason everything he was doing in this video just went over my head. I didn't understand why he was doing anything he did in the video. I don't know if he just didn't explain it well or what. I was hoping you guys here could explain to me what Member Initializers are, in hopes that I could maybe understand your guys' explanation of it better :)

It is because constant data members or variables that reside in a class, cannot be initialized in the class without the member initialization list.

Consider:
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
// This would not work because you cannot initialize constant variables in a class without the member initializer list

class initVars {
private:
	const int var1;
	string var2;

public:
	initVars(int v1, string v2)
	{
		var1 = v1;
		var2 = v2;
	}

	void printVars ()
	{
		cout << var1 << endl;
		cout << var2 << endl;
	}
};

int main() 
{
	initVars iV(1, "Hi"); // Creating the object, and calling the constructor with the two variables discussed above.
	iV.printVars();
}


The above code would produce the following error:
 
must be initialized in constructor base/member initializer list


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
// This would work because you use member initialization list to initialize the const data member
 
class initVars {
private:
	const int var1;
	string var2;

public:
	initVars(int v1, string v2)
		: var1(v1), // Here, C++ Says "Constructor, make var1 and var2 equal to the arguments given by the constructor.
		var2(v2)
	{
		var1 = v1;
		var2 = v2;
	}

	void printVars ()
	{
		cout << var1 << endl;
		cout << var2 << endl;
	}
};

int main() 
{
	initVars iV(1, "Hi"); // Creating the object, and calling the constructor with the two variables discussed above.
	iV.printVars();
}
Last edited on
Thanks guys. This helped me out a lot :)

I'm still a bit confused, but not nearly as much as I was before. I think I'll figure it out soon, though :)
Topic archived. No new replies allowed.