1

This question may seem a little bit to broad, because it is a subject that splits into:

1. returning by value

  1. returning by reference
  2. 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.


  1. 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 by copy constructor to appear, instead just the first one did.

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;
}

  1. The previous question arises after trying to implement the following operator+ function
    • Each time obj1 + obj2 is going to execute, this operator+ function is going to return a temporary object by value. Here it should call the copy constructor, but instead, the classic constructor is also called.

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.

Cătălina Sîrbu
  • 1,253
  • 9
  • 30
  • I cant help you right now, but maybe this (admittedly long) video helps a bit: https://www.youtube.com/watch?v=OwDJGrV3pgM&list=PLqCJpWy5Fohfil0gvjzgdV4h29R9kDKtZ&index=13 – Vandrey Apr 09 '20 at 11:01
  • 1
    for returning a reference/pointer the main issue that often leads to problems is returning a reference/pointer to an object that is local to the function, because its lifetime ends when the function returns, But you should really concentrate on one question per question. Asking multiple questions at once leads to situations like having a duplicate that answers one but not the others – 463035818_is_not_an_ai Apr 09 '20 at 11:02

0 Answers0