I'm learning about the copy constructor and I'm having a little difficulty understanding some things. I have three questions for anyone gracious enough to answer:
They all have the same question: Why the copy-ctor is not called
Using this class:
class Bar {
public:
inline Bar(const Bar& x) {
std::cout<<"copy constructor\n";
}
inline Bar() {
std::cout<<"default constructor\n";
}
};
...
Question 1:
Please explain to me why the following does not call the copy constructor (aside from calling the default one)?:
int main( int argc, char**argv )
{
Bar x = Bar();
return 0;
}
My thoughts were that the copy ctor would also be called because the right operend is returning an newly created object by
value and it matches the copy ctors parameter arguments so, this temp value object would be passed by reference, and the left object
x would be the
this pointer in the copy ctor and thus, print the "copy constructor" string, after printing the "default constructor" string.
As a backup to go with the example, My C++ Primer books states the following: "Copy-initialization uses the = symbol" ..."Copy-initialization always involves the copy constructor"
Question 2:
I have the same question for the following also:
void X(Bar x) { /*...*/ }
int main( int argc, char**argv )
{
X(Bar());
return 0;
}
Question 3:
Last but not least, return by value does not call my copy ctor:
Bar Y(void)
{
Bar y;
return y;
}
int main( int argc, char**argv )
{
Y();
return 0;
}
If the object being returned instead is from the functions parameter (and not declared locally), it does call the copy ctor on return. Hmm.
As always, Thanks in advance.
- xeddiex