Here is a simple class header file and main program. In the main program, I thought that the copy constructor is called in exactly three situations: initialization (explicit copy), passing by value for function arguments and returning by value for functions. However, it seems that it is not called for one of them, I think that either (3) or (4), as indicated in the comments. For which numbers (1) - (4) is it called? Thanks.
Xh:
#include <iostream>
class X
{
public:
X() {std::cout << "default constructor \n";}
X(const X& x) { std::cout << "copy constructor \n";}
};
Main:
#include "X.h"
X returnX(X b)
{
X c = b;
return b;
}
int main()
{
X a;
std::cout << "calling returnX \n\n";
X d = returnX(a);
std::cout << "back in main \n";
}
Output:
default constructor
calling returnX
copy constructor
copy constructor
copy constructor
back in main
source
share