I have the following c++ code (VS2013):
#include <iostream>
using namespace std;
class A {
int i;
public:
A(int i) : i(i) {
cout << "Constructor: " << i << endl;
}
A(const A &o) : i(o.i) {
cout << "Copy constructor: " << i << endl;
}
~A() {
cout << "Destructor: " << i << endl;
}
};
A test(const A &a, A b, A *c) {
return *c;
}
int main() {
A b(10);
cout << "START OF TEST" << endl;
test(1, b, &b);
cout << "END OF TEST" << endl;
system("pause");
}
When running the code, I get the following output between the "START OF TEST" and "END OF TEST" outputs:
Constructor: 1
Copy constructor: 10
Copy constructor: 10
Destructor: 10
Destructor: 10
Destructor: 1
3 objects are built: 1 using an integer 1
, and 2 using an object of class A
(with i = 10).
It's worth mentioning that when the test
function's argument const A &a
is changed to A &a
(not a constant), the program does not compile, giving the following error:
Error C2664: 'A test(A &,A,A *)' : cannot convert argument 1 from 'int' to 'A &'
How is this behavior explained?
Specifically:
Why does sending an integer
1
totest
make A's parameter constructorA(int i)
work (and only whenconst
is used)?Why does A's copy constructor A(const A &o) work twice? (one run occurs when calling
test
, and another when returning*c
).