How a constructor works

Hello, I'm new to programming and I'm learning the C++ programming language. Today I'm here because I have some problems in understanding the basics about constructors. I just started learing about classes and I have some questions :

I'm studying from the book : Programming principles and pratice using C++ and in chapter 9 the author introduces to classes and constructors, to let the readers understand these concepts better the author uses this example of a Date class :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 class Date {
public: 
	Date(int yy, int mm, int dd) :y{ yy }, m{ mm }, d{ dd } {};
private: 
	int y; 
	int m; 
	int d; 
};

int main()
{
   Date today{2015, 9, 20}; 



}


I got some confusion about this because after this example the author explains that this notation used to intialize the data members y,m,d is more direct than the notation :
1
2
3
4
5
6
7
8
9

Date(int yy, int mm, int dd) {

	y = yy; 
	m = mm; 
	d = dd; 

}


Because the second kind of notation first default initialises the data members of Date then changes their value. But this sentence got me in cofusion, what does exactly happens when I initialize a Date object ? I go into the body of the constructor or something happens before ? Why the first notation is better than the second one ? When I use intializer list am I using calling the constructor ?
Last edited on
what does exactly happens when I initialize a Date object ? I go into the body of the constructor or something happens before ?
When object is constructed, following happens: first, all members are initialized. If you provide it, values from init list are used, else they are default initialized. Then constructor body is executed.

Why the first notation is better than the second one ?

Difference between using init lists and initialization in constructor body is like difference between following:
1
2
3
4
int i = 5;
//and
int i = 0;
i = 5;
For primitive types, like int it does not really matter, but for more complex ones double initialization can lead to slowdown. Also there are classes which cannot be default constructed at all.

Well pretty much calling the constructors as is. This line of code.

 
:y{ yy }, m{ mm }, d{ dd } {};


is pretty much a more fancy way of doing this.
1
2
3
4
y = yy; 
	m = mm; 
	d = dd; 
//It will work just the same as doing it in the constructor. 


Then if you would like to change the values in the constructors like 2015,9,20. Pretty much you could use the private variables inside your class to call arguments within the constructor in main.
//It will work just the same as doing it in the constructor.
Only for primitive types. Anything complex and it is not same: less efficient and sometimes impossible.
Topic archived. No new replies allowed.