When I run this code it prints one X. That is when u is defined as a variable of type Uno. What I'm wondering is why there is no X printed when e is defined as a variable of type Uno? It does so when I change the function to:
#include <iostream>
using std::cout;
using std::cin;
class Uno {
public: Uno() {
cout << "X";
}
};
Uno foo(Uno d){
Uno e = d;
return e;
}
int main(){
Uno u;
foo(u);
return 0;
}
Maybe that this behavior is due to your compiler's optimizing process. I compiled and ran your code with your claimed changes at cpp.sh and there I got 'XX'.
#include <iostream>
using std::cout;
using std::cin;
class Uno {
public: Uno() {
cout << "X";
}
};
Uno foo(Uno d){
Uno e;
e = d;
return e;
}
int main(){
Uno u;
foo(u);
return 0;
}
Compile and run this by clicking on the gearwheel at right beside the code window, and you will get two X.
rob: you're not running the same program as OP, specially your lines 13-14 vs OP line 13. OP code at shell gives single X: http://cpp.sh/3rm7f. guess why?
Yes, it's not the same version then the OP's posted code . But i interpreted the OP's text in such manner that he at first tried a code example like mine whereby he would missing a second X. And I think that a single X at the OP's posted code is correct behavior. Think you that's not the case?
When you declare Uno u; your are invoking the... how can I call it?... ‘normal’ constructor, which prints an ‘X’ on the screen.
When you declare Uno e = d; you are invoking the copy constructor, which you haven’t defined, so it’s automatically provided by the compiler to perform the basic copy operations.
If you add a copy constructor, you can see when it’s invoked:
The copy constructor is invoked twice, the first time when you call foo(u); from inside main(), because you pass a copy of ‘d’, and another one from the instruction Uno e = d; inside foo().