Tag Archives: function chaining

Function Chaining in C++

Function chaining is a construct inĀ  C++. It constructs a chain of function calls in one statement. Return value of the previous function call is used to call the next function and hence a chain of function calls is created. Following is an example of it:

obj.func1().func2().func3();

obj.fun1() is an expression which evaluates to the return-value of func1(). On this returned-value func2() is called which again evaluates to its return value. Similarly func3().

Function chaining is good as well as bad. It may make the code look compact and nice but excessive use may end up with readability and maintenance issues. The code may be difficult to debug also. One can’t see the intermediate return values of the function calls.

Apart for the readability and debugging issues, it can also result into a serious memory issue. Lately, I faced it while converting from a QString to a char* C string. Here is the code:

// function QString::toLocal8Bit() returns QByteArray
// QByteArray::data() returns pointer to internal data

QString str("manjeet");
const char *c_str = str.toLocal8Bit().data();
// c_str is now a dangling pointer referring to an invalid memory

In the above code c_str points to an invalid memory.

It happens because the function chaining involves unnamed temporary objects. These unnamed temporary objects are returned by the function calls. And these are again used to call the next function call. But in this case the last temporary object is not stored and is deleted after the statement is complete.

This code can be fixed by avoiding the function chaining and storing the intermediate object.

QString str("manjeet");
QByteArray ba = str.toLocal8Bit();
const char *c_str = ba.data();

Here the problem is fixed as the byte array is now being stored the ba variable.

[1] http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr382.htm

[2] http://stackoverflow.com/questions/154864/function-chaining-how-many-is-too-many