First of all, I am not at all an experienced C++ programmer, I am just trying to pass my OOP exam. It is not very clear for me when the copy constructor is called. I knew that there are some "special" cases when giving argument by value to a functions, and when returning by value. Here, where I give arguments by value to void F(A x)
everything happens as expected:
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(int x = 0) {
x = x;
cout<<"Constructor "<<x<<endl; }
~A(){
cout<<"Destructor "<<endl; }
A(const A&o){
x = o.x;
cout<<"Copy constructor"<<endl;
}
};
A F(){
A a;
return a;
}
void F(A x){
}
int main()
{
//A obj(F());
A a;
F(a);
}
///
The output is:
Constructor 0
Copy constructor
Destructor
Destructor
Because the Constructor 0
is showed when declaring A a
, the copy constructor and the destructor are showed because of the function call, cause the parameter is passed by value, and the final destructor is the destructor for a
.
It is not very clear for me why in the next case the behaviour is so different:
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(int x = 0) {
x = x;
cout<<"Constructor "<<x<<endl; }
~A(){
cout<<"Destructor "<<endl; }
A(const A&o){
x = o.x;
cout<<"Copy constructor"<<endl;
}
};
A F(){
A a;
return a;
}
void F(A x){
}
int main()
{
A obj(F());
}
///
Now, the output is:
Constructor 0
Destructor
It seems like only the A a
inside the A F()
is called. Why isn't the copy constructor called when calling F()
? Doesn't it return by value, isn't the copy constructor called ? Moreover, when declaring A obj(F())
why isn't the copy constructor called at leas for obj
?