Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Constructor initialization list strangeness

I have always been a good boy when writing my classes, prefixing all member variables with m_:

class Test {
    int m_int1;
    int m_int2;
public:
    Test(int int1, int int2) : m_int1(int1), m_int2(int2) {}
};

int main() {
    Test t(10, 20); // Just an example
}

However, recently I forgot to do that and ended up writing:

class Test {
    int int1;
    int int2;
public:
    // Very questionable, but of course I meant to assign ::int1 to this->int1!
    Test(int int1, int int2) : int1(int1), int2(int2) {}
};

Believe it or not, the code compiled with no errors/warnings and the assignments took place correctly! It was only when doing the final check before checking in my code when I realised what I had done.

My question is: why did my code compile? Is something like that allowed in the C++ standard, or is it simply a case of the compiler being clever? In case you were wondering, I was using Visual Studio 2008

like image 669
Andy Avatar asked Mar 19 '10 10:03

Andy


People also ask

Does initializer list run before constructor?

As already answered, initialization lists get completely executed before entering the constructor block. So it is completely safe to use (initialized) members in the constructor body.

What is initialization list in constructor?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

Why initialization list is used in C++?

Initialization lists allow you to choose which constructor is called and what arguments that constructor receives. If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

What is an initialization list in C++?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.


1 Answers

Yes, it's valid. The names in the member initializer list are looked up in the context of the constructor's class so int1 finds the name of member variable.

The initializer expression is looked up in the context of the constructor itself so int1 finds the parameter which masks the member variables.

like image 127
CB Bailey Avatar answered Sep 22 '22 10:09

CB Bailey