order of constructors called in a function

96 views Asked by At

I would like to ask for a clarification of the constructors calls order in the following program.

What I tried:
The output starts with 1 3 2. I tried to debug it to see why the function "f" calls the 3rd argument's ctor before the 2nd's and I don't really get it.
I tried to put the argument "1" as the last one (of-course I also changed the function signature as needed) and still, "1" is the first argument calls it's ctor.
I tried to do different orders of calls and have some assumption about whats going on.

It seems like it calls the ctors from the last argument to the first while the argument isn't an int (float etc..) type, if it is one of these types it calls their ctor first in the same order (from last to first while passing over the others)

So, any thoughts? I would like to know what is really going on. Thanks.

#include <conio.h>
#include <iostream>
using namespace std;

class A {
int i;
public:
    A(int i) : i(i) {
         cout << i << endl;
    }
    A(const A &o) : i(o.i) {
        cout << i << endl;
    }
    ~A() {
        cout << i << endl;
    }
    friend A f(const A &, A , A *);
};

A f(const A &a, A b, A *c) {
    return *c;
}

void main() {
    f(1, A(2), &A(3));
}
1

There are 1 answers

4
Ron On

The order of evaluation of function arguments is unspecified in C++. It does not go from left to right. When you have a function accepting multiple parameters:

void foo(A a, B b, C c);

it doesn't mean the parameters will be evaluated in the a -> b -> c order. Don't confuse the function signature (evaluation) with the block of statements (execution) inside the function definition.

Also, taking an address of a temporary as you have with the &A(3) should result in error, you don't need the <conio.h> header and you should avoid using the using namespace std;.