Return type of a method

Hello,
I have a question about return types.
So suppose we have a class NameClass that has as private attributes list<thing1> and that i want to create a method that adds to a "new thing" to the list.
so

"return type " NameClass::addThing(const thing1& t).
would it make sense to have the return type as NameClass& and return *this
or should i just have the return type as void?

Thanks for the help.

Last edited on
looks like a void from your description. you call it, and it adds one, and you have another function to get the list via a 'getter' function, right?


> would it make sense to have the return type as NameClass& and return *this

Yes. It would allow one to chain operations on an object; this could make the code more readable. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
#include <list>
#include <cctype>

struct text
{
    text& append( std::string str ) { lines.push_back( std::move(str) ) ; return *this ; }

    text& toupper()
    {
        for( auto& str : lines ) for( char& c : str ) c = std::toupper(c) ;
        return *this ;
    }

    std::ostream& print( std::ostream& stm = std::cout ) const
    {
        for( const auto& str : lines ) stm << str << '\n' ;
        return stm ;
    }

    std::list<std::string> lines { "one", "two", "three", "four" } ;
};

int main()
{
    text txt ;

    txt.append("five").toupper().print() ;
}


The drawback is that facilitating chained operations expects a certain level of maturity from the users of the class.
For example, this would engender undefined behaviour prior to C++17:
1
2
int i = 10 ;
std::cout << i << i++ << '\n' ; // chaining is possible because operator<< returns std::ostream& 


I think that with the advent of C++17 - http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0145r3.pdf - return *this ; to enable chaining of function calls should be the norm.
Topic archived. No new replies allowed.