I got the following code:
class Book
{
public:
void print();
const Book &Book::get();
};
void Book::print()
{
cout << "print()" << endl;
}
const Book &Book::get()
{
cout << "get()" << endl;
return *this;
}
Then I did:
Book b;
b.get().print(); // This did not work. Why is that?
It can call other functions, but not in this case.
You’re returning a
const Book &fromget(). This is then callingprint(), which is a non-const function. To fix this, makeprint()const:This const ensures your object’s state will not be changed, which complies with the const object you return from
get(). Note that it can changemutablemembers though, as that’s their whole purpose.Edit:
By the way, the term you’re looking for is
method chaining.