Re: using sub-objects to initialize other sub-objects
On 28 Okt., 06:05, "terminator(jam)" <farid.mehr...@gmail.com> wrote:
Is that legal ?
I mean something like this:
struct A{
int a,b;
A():
a(5),
b(2*a) //Is this standard?
{
std::cout<<a<<' '<<b<<std::endl;
};
};
Yes this is "legal" and has defined behaviour (i.e.
A::b == 10 after the initialisation), because of [class.base.init]/5:
"Initialization shall proceed in the following order: [..]
- Then, nonstatic data members shall be initialized in the order
they were declared in the class definition (again regardless of the
order of the mem-initializers).[..]"
in combination with [class.base.init]/3:
"[..] There is a sequence point (1.9) after the initialization of
each
base and member. The expression-list of a mem-initializer is
evaluated
as part of the initialization of the corresponding base or member."
In your example A::a is declared *before* A::b and this guarantees
that it's initialization happens before that of A::b or vice-versa:
The
initialization of b can trust that a is completely initialized. The
above
quoted paragraph also provides similar guarantees for base-classes
of the corresponding class, which I have omitted here for clarity.
If you want to irritate the reader of your class, you also could
have written:
struct A{
int a,b;
A():
b(2*a),
a(5)
{
std::cout<<a<<' '<<b<<std::endl;
}
};
which has exactly the *same* effect as your original code
(but don't tell your colleagues that I recommended this!).
Greetings from Bremen,
Daniel Kr?gler
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]