Is there a name for this:
class A
{
A* setA()
{
//set a
return this;
}
A* setB()
{
//set b
return this;
}
};
so you can do something like this:
A* a = new A;
a->setA()->setB();
Are there any drawbacks to using this? Advantages?
It’s known as method chaining (FAQ link), and is more commonly done with references, not pointers.
Method chaining is strongly associated with the Named Parameter Idiom (FAQ link), as I now, after posting an initial version of this answer, see that Steve Jessop discusses in his answer. The NPI idiom is one simple way to provide a large number of defaulted arguments without forcing complexity into the constructor calls. For example, this is relevant for GUI programming.
One potential problem with the method chaining technique is when you want or need to apply the NPI idiom for classes in an inheritance hierarchy. Then you discover that C++ does not support covariant methods. What that is: when you let your eyes wander up or down the classes in a chain of class inheritance, then a covariant method is one whose definition involves some type that to your wandering eye varies in specificity in the same way as the class it’s defined in.
It is about the same problem as with defining a
clonemethod, which has the same textual definition in all classes, but must be laboriously repeated in each class in order to get the types right.Solving that problem is hard without language support; it appears to be an inherently complex problem, a kind of conflict with the C++ type system. My “How to do typed optional arguments in C++98” blog post links to relevant source code for automating the generation of covariant definitions, and to an article I wrote about it in Dr. Dobbs Journal. Maybe I’ll revisit that for C++11, or sometime, because the complexity and possible brittleness may appear as a larger cost than it’s worth…