This question may seem a little bit to broad, because it is a subject that splits into:
1. returning by value
- returning by reference
- returning by pointer
And I'm not sure that I'll be able to understand without knowing all of the points (1,2 and 3), so providing some useful links would be awesome. I did search for topics like "returning from functions in C++" but only found some basic examples where things were presented superficially.
- It is unclear for me why returning an user_defined object by value from a function does not call the copy constructor
- I was expecting
classic constructor
message followed bycopy constructor
to appear, instead just the first one did.
- I was expecting
class X
{
public:
int val;
X(int val) : val{val} { cout << "classic constructor\n";}
X(const X& ref) : val{ref.val} { cout << "copy constructor\n"; }
};
// function returning an object of type X by VALUE
X f()
{
X a = X{6};
return a;
}
int main()
{
X obj = f();
return 0;
}
- The previous question arises after trying to implement the following
operator+
function- Each time
obj1 + obj2
is going to execute, thisoperator+
function is going to return atemporary
object by value. Here it should call the copy constructor, but instead, theclassic constructor
is also called.
- Each time
X operator+(const X& ref1, const X& ref2)
{
X var_temp{ref1.val + ref2.val};
return var_temp;
}
I feel like I misunderstood how does returning from function works. Maybe you could help me to better understand this.
Thanks in advice.