Chaining method; Return a pointer vs. a reference?

advertisements

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");


The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.