difference between initialzing in the constructor and in the member initializer

+1 Bat Man · January 21, 2016
meant to ask this before: what is the difference between member initializer (the double colons thing before the body) and actually initialzing the values in the constructor? In this example: why write

birthday::birthday(int d, int m, int y) {
    day = d;     
    month = m;    
    year = y;

 instead of

birthday::birthday(int d, int m, int y)
:day(d), month(m), year(y)
{ } 

in the birthday class? like he did in the people class? from previous videos i know that if the attribute is a const, then you need the member initialzer, but if it's a regular variable, what is the difference? both ran with no error and same output btw.

Post a Reply


Oldest  Newest  Rating
0 Minh Nguyen · January 21, 2016
When you have this
Birthday::Birthday(int d, int m, int y) {

Your day, month and year members have garbage values before the body itself. After the function body is executed, they will have the values that you specify

// assuming you have members Person person and Job job
Birthday::Birthday(int d, int m, int y, char* name) : person(name), job() {

Here the default constructor is called for class Job and constructor that takes char* as parameter for Person.

Basically in the second example the member variables are guaranteed to be initialized first (not having any default value, but the ones you specify) and in the order that you want, while in the first one your variables have garbage values and then you assign to them the appropriate values. That is the only difference I think
0 Bat Man · January 22, 2016
Thx a lot guys!!
0 Minh Nguyen · January 22, 2016
@Krootushas Gesu Thanks, corrected my answer :)
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator