Quantcast
Channel: Active questions tagged return-value - Stack Overflow
Viewing all articles
Browse latest Browse all 206

How to use objects in C++ correctly

$
0
0

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


Viewing all articles
Browse latest Browse all 206

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>