james ray
james ray

Reputation: 117

Difference between returning a reference and modifying a class directly?

I have looked at the disassembly for the following code and found that the result is often the same (or very similar) for both test functions. I am wondering what the difference is between the two functions and if not, is there any history or reason for this existing?

struct test
{
    int x;

    test&      testfunction1()  { x++; return *this; }
    void       testfunction2()  { x++; }
};

edit: with my question being answered so quickly I am now wondering what reasons you would choose to use one over the other? it seems for the sake of 'freedom' one should always use a reference over the directly modifying the data.

Upvotes: 1

Views: 95

Answers (1)

ygroeg
ygroeg

Reputation: 323

The functionality is almost the same, difference is the first enables the ability to chain methods. This design pattern is called fluent interface. It is supposed to provide an easy-readable, flowing interface, that often mimics a domain specific language. Using this pattern results in code that can be read nearly as human language.

Widget w = new Widget();
w.setHeight(1024).setWidth(768).setColor(255,0,0); // easy to follow

Why people don't do it everywhere? It is matter of preference, readability, coding convention of the group, it takes more effort to design you API in such way. Also if you don't use the returned value, it can produce warning or error expression result is unused when compiling C++ with some flags.

The common usage of testfunction1() example is using of overloaded operators of output for something, often you can see in code

std::cout << "The results are: " << SomeUserDefinedStruct << " and "<< SomeUserDefinedStruct2 << std::endl;

The overloaded version of operator<< is returning reference to std::ostream, which is chained to others.

Upvotes: 2

Related Questions