Can someone clarify/correct me on why certain functions such as push_back() do not need an assignment to output the new string, while a function such as substr() needs to be assigned to a string in order for the output to be the new subs-string? For example:
string givenInput;
char addChar;
getline(cin, givenInput);
cin >> addChar;
givenInput.push_back(addChar);
cout << givenInput << endl;
This example outputs the new string without having to do givenInput = givenInput.push_back(addChar);. However, when doing something like:
string strVal;
int beginIndex;
int selectionLen;
getline(cin, strVal);
cin >> beginIndex;
cin >> selectionLen;
strVal = strVal.substr(beginIndex, selectionLen);
cout << strVal << endl;
Why is that I need to assign strVal rather than simply having the line strVal.substr(beginIndex, selectionLen); and then outputting cout << strVal?
I hope what I'm asking makes sense, and if anyone could clarify why this is, that would be greatly appreciated, thanks!
Those are two different styles of method. Some methods, like std::string::push_back() modify the object they are called upon. Other methods, like std::string::substr(), do not modify the object they are called upon, but rather create a new
std::stringobject and return it. It's up the person/committee implementing a class to decide which style(s) of method they want to provide.In order to find out what each method does, you need to read its documentation; however, in this case, a very good hint that a method does not modify the object that it is called upon is the presence of a
constkeyword at the end up the method's signature, like this:That
constkeyword at the end is basically a promise that the compiler will not allow this method to modify the object it is called upon (caveat: the method's implemention could "cheat" and use theconst_cast<>ormutablekeywords to modify it anyway, but we'll ignore that possibility for now since most coders know better than to do that without a really compelling reason).