c++return-value

How to use objects in C++ correctly


After finally having learnt most of the basics of C++, there is still on puzzle part which is missing. Let's take for example:

class MyClass {
/// ...
};

void f1(MyClass& cl) {
}

void main() {
  MyClass cl; // Calls the constructor
  MyClass *ptr = nullptr; // Declares a pointer.
  ptr = &cl;  // Now points to the object above.
  f1(cl); // working by mentioning the object
  f1(*ptr);  // working by dereferencing.
}

Now, I do not understand what to do when a function is returning a simple class name (not a pointer like MyClass * and not a reference like MyClass&:

MyClass f3() {
  MyClass c = nullptr; // is this even allowed?
  // .... Within the function, c gets assigned to some other already existing object.
  return c;
}

// caller:
MyClass c = f3();
MyClass *ptr = ?????; // <--- what comes here to invoke f3()?
MyClass& ref = ?????; // <--- what comes here to invoke f3()?

So, my question is, how to assign the return value of a function whose return value is of type MyClass (not pointer, not reference) to a pointer or a reference in the caller? Does MyClass obj = nullptr even make sense, or should I prefer modifying the function to return MyClass *?


Solution

  • MyClass f3() {
      MyClass c = nullptr; // is this even allowed?
      // .... Within the function, c gets assigned to some other already existing object.
      return c;
    }
    

    In the above case, it doesn't make any sense because c is not a pointer.

    Later c is returned by value, so a copy is made. This is easy is MyClass is a trivial class, but if the class has dynamically allocated memory you'll want to read up on the rule of three/five/zero.