Re: Member Initialization Gotcha!
- From: David Wilkinson <no-reply@xxxxxxxxxxxx>
- Date: Sun, 16 Nov 2008 06:48:43 -0500
Tommy wrote:
Here is one for the C++ brainaics. :-)
This only took a few hours to figure out after I finally went back to MSDN and saw this warning regarding member initialization:
Warning: The order in which the member initializers are
specified in the constructor does not affect the order in
which the members are constructed; the members are constructed
in the order in which they are declared in the class.
So you would think that two protected const DWORD members shown here would be constructed in its declared order:
class CFooBar {
public
CFooBar(const DWORD d)
: D1(d+10), D2(D1)
{}
protected:
const DWORD D2;
const DWORD D1;
}
Correct?
Well, never mind the above uses D1 to initialize D2, the above is drastically reduce code for illustration. There was a reason for
D2(D1).
What I found is that I had to reverse the order of the member declaration to get it initialize correctly. So with D2 declared first, it would not initialize correctly.
Reversing it like so:
protected:
const DWORD D1;
const DWORD D2;
make it initialize correctly. So if I read the warning right, it would be incorrect because there is indeed a order dependency in order to get the correct member initialization.
Correct?
It showed up when the original constructor:
CFooBar(const DWORD d)
: D1(d+10)
{
D2 = D1;
}
was changed to the above during my port to VC8 code clean up which I better stop doing. :-)
Tommy:
You changed the order of declaration in the class, and the behavior changed (to the one you wanted). How does that contradict the warning?
Personally, I think that initialization that depends on the order of declaration is very fragile, and I would either stick with your original
CFooBar(const DWORD d):
D1(d+10)
{
D2 = D1;
}
or do
CFooBar(const DWORD d):
D1(d+10),
D2(d+10)
{
}
--
David Wilkinson
Visual C++ MVP
.
- Follow-Ups:
- Re: Member Initialization Gotcha!
- From: Tommy
- Re: Member Initialization Gotcha!
- References:
- Member Initialization Gotcha!
- From: Tommy
- Member Initialization Gotcha!
- Prev by Date: Re: pugXML parser - dumping to XML
- Next by Date: Re: Member Initialization Gotcha!
- Previous by thread: Member Initialization Gotcha!
- Next by thread: Re: Member Initialization Gotcha!
- Index(es):
Relevant Pages
|