[c++] Method Call Chaining; returning a pointer vs a reference?

I have a Text class that has certain methods that return a pointer to itself, allowing calls to be chained. (The reason being I merely like how the chaining looks and feels, honestly!)

My question is, which is generally better in practice (in terms of safety > versatility > performance)? Returning and using References? Or Returning and using Pointers?

An example of both, starting with the Pointer version:

class Text{ public:     Text * position(int x, int y){         /* do stuff */         return this;     }     Text * write(const char * string);     Text * newline();     Text * bold(bool toggle);     Text * etc();     ... };  textInstance.position(0, 0)->write("writing an ")->bold(true)->write("EXAMPLE"); textInstance.position(20, 100)            ->write("and writing one across")            ->newline()            ->write("multiple lines of code"); 

versus the Reference version:

class Text{ public:     Text & position(int x, int y){         /* do stuff */         return *this;     }     Text & write(const char * string);     Text & newline();     Text & bold(bool toggle);     Text & etc();     ... };  textInstance.position(0, 0).write("writing an ").bold(true).write("EXAMPLE"); textInstance.position(20, 100)             .write("and writing one across")             .newline()             .write("multiple lines of code"); 

This question is related to c++ pointers reference coding-style return

The answer is


It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.


Since nullptr is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.


Very interesting question.

I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.

But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to pointers

Method Call Chaining; returning a pointer vs a reference? lvalue required as left operand of assignment error when using C++ Error: stray '\240' in program Reference to non-static member function must be called How to convert const char* to char* in C? Why should I use a pointer rather than the object itself? Function stoi not declared C pointers and arrays: [Warning] assignment makes pointer from integer without a cast Constant pointer vs Pointer to constant How to get the real and total length of char * (char array)?

Examples related to reference

Method Call Chaining; returning a pointer vs a reference? When to create variables (memory management) Reference to non-static member function must be called Cannot find reference 'xxx' in __init__.py - Python / Pycharm c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration) C++ initial value of reference to non-const must be an lvalue Dependent DLL is not getting copied to the build output folder in Visual Studio How to write to error log file in PHP How to reference Microsoft.Office.Interop.Excel dll? Linker Error C++ "undefined reference "

Examples related to coding-style

Method Call Chaining; returning a pointer vs a reference? 80-characters / right margin line in Sublime Text 3 Cannot find reference 'xxx' in __init__.py - Python / Pycharm How to stick <footer> element at the bottom of the page (HTML5 and CSS3)? Simple way to create matrix of random numbers Is calling destructor manually always a sign of bad design? Count all values in a matrix greater than a value Iterate through a C++ Vector using a 'for' loop Which comment style should I use in batch files? Dictionaries and default values

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)