The copy constructor is called because you call by value not by reference. Therefore a new object must be instantiated from your current object since all members of the object should have the same value in the returned instance.
The point of "pass by reference" is to not make a copy as soon as Employee constructor is called, but only when you choose to initialize one of Employee's member with the Date passed.
A copy constructor defines what copying means,So if we pass an object only (we will be passing the copy of that object) but to create the copy we will need a copy constructor, Hence it leads to infinite recursion. So, A copy constructor must have a reference as an argument.
In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value. 2) When an object of the class is passed (to a function) by value as an argument. 3) When an object is constructed based on another object of the same class.
References in C++ are baffling me. :)
The basic idea is that I'm trying to return an object from a function. I'd like to do it without returning a pointer (because then I'd have to manually delete
it), and without calling the copy-constructor, if possible (for efficiency, naturally added: and also because I wonder if I can't avoid writing a copy constructor).
So, all in all, here are the options for doing this that I have found:
MyClass fun() { ... }
) or a reference to the class (MyClass& fun() { ... }
).return MyClass(a,b,c);
) or return an existing variable (MyClass x(a,b,c); return x;
).MyClass x = fun();
or MyClass& x = fun();
)MyClass x = fun();
) or assign it to an existing variable (MyClass x; x = fun();
)And some thoughts on that:
MyClass&
because that always results in the variable being destroyed before it gets returned.These results are so inconsistent that I feel totally confused. So, what EXACTLY is happening here? How should I properly construct and return an object from a function?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With