Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does C++ string erase return *this mean?

Tags:

c++

string

erase

So the C++ string function

string& erase ( size_t pos = 0, size_t n = npos )

returns *this. What does that mean? Why do I need it to return anything?

Example

string name = "jimmy";  
name.erase(0,1);

will erase j and become immy, but why do I need it to return anything at all?

like image 539
bluejimmy Avatar asked Dec 01 '22 20:12

bluejimmy


2 Answers

For method chaining. For example, after you erase, you can call == on it to check something:

string name = "jimmy";
bool b = name.erase(0,1) == "immy";
like image 184
Luchian Grigore Avatar answered Dec 04 '22 09:12

Luchian Grigore


It is only for convenience, for example you can chain calls like this:

name.erase(0,1).erase(3,1);
like image 22
Matzi Avatar answered Dec 04 '22 09:12

Matzi