pasha pasha - 27 days ago 5
C++ Question

If two objects are declared in a single line, in what order are they constructed?

Let's say a class has been defined as

class A {
//.....
};


and now I am creating two objects as

A a,b;


In what order are
a
and
b
created? Is it defined by the standard?

Answer

From 8 Declarators [dcl.decl] 3:

Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.

It goes on to say

A declaration with several declarators is usually equivalent to the corresponding sequence of declarations each with a single declarator. That is T D1, D2, ... Dn; is usually equivalent to T D1; T D2; ... T Dn; where T is a decl-specifier-seq and each Di is an init-declarator. An exception occurs when a name introduced by one of the declarators hides a type name used by the decl-specifiers, so that when the same decl-specifiers are used in a subsequent declaration, they do not have the same meaning.

You can say that they are constructed from left to right.

Comments