PDA

View Full Version : Useless but curious compiler warning question


Raccoon29
29th July 2008, 10:56
Hi, here is a tea question:

the warning in subject is "class::constname will be initialized after const type class::secondconstname when initialized here [the initialization row]"

Situation:
let's suppose that we declare two constant variables in a class
class myCuriousClass{
private:
const int constant1;
const int constant2;
public:
myCuriousClass();
};
and then we valorize them as expected within a class: by the constructor
myCuriousClass::myCuriousClass()
:constant2(2),constant1(1)
{
//nothing smart to do here
}
the fact that we initialized them in reversed order than we declared them makes the compiler complain myCuriousClass::constant1 will be initialized before const int myCuriousClass::constant2 when initialized here (row 3 of the second piece of code)
So the question is, what is the problem if I reverse the order? Why was dedicated a warning to this situation?

PS: for this test I used a MinGW compiler.

Thank you for your attention

jpn
29th July 2008, 11:18
Imagine if there's a dependency between member variable initialization. Let's say member variable A is passed to the constructor of member variable B. Initializing them in wrong order might lead to passing an uninitialized variable.

Raccoon29
29th July 2008, 11:27
Just for this?
Actually I believed there were deeper reasons :D
Thank you anyway

wysota
29th July 2008, 11:56
Actually I believed there were deeper reasons :D

It's a warning, not an error.

caduel
30th July 2008, 21:46
The order you write suggest both to you and the readers of your code that the variables will be initialized in that order.
The order, however, is defined by the declaration of the class, not the initializer list of a constructor implementation.

So, if the order is not correct and the code might depend upon the order of initialization you get a warning so you can make sure there is no such problem.