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 *
?