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?
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?
Standards:
Declarators [dcl.decl]:
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
Example:
class A {
public:
A(std::string const &s): name(s)
{
std::cout << "I am " << name << '\n';
}
std::string name;
};
auto main() -> int
{
A a("a"), b("b");
}
Output:
I am a
I am b
a will be created first and then b.
Commas in this case will be used as separators and not as operators.
For example from wikipedia :
/**
* Commas act as separators in this line, not as an operator.
* Results: a=1, b=2, c=3, i=0
*/
int a=1, b=2, c=3, i=0;
The order is the written order, from left to right. Also, it's not the comma operator, but simply a list of declarators. When a user-defined comma operator is used, order is in fact unspecified.
See comma operator and declarators.
C++ spec chapter 8 [dcl.decl], says:
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself. (100)
Footnote (100) goes on to say:
(100) 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;
...and then names some exceptions, none of which apply in such simple cases.
So the answer to your question is that the objects are constructed in the order you list them. And no, it is not a comma operator.
From 8 Declarators [dcl.decl] 3:
It goes on to say
You can say that they are constructed from left to right.