Reputation:
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!
Upvotes: 0
Views: 65
Reputation: 73279
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::string
object 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 const
keyword at the end up the method's signature, like this:
basic_string substr( size_type pos = 0, size_type count = npos ) const; <-- note const keyword at end!
That const
keyword 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 the const_cast<>
or mutable
keywords 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).
Upvotes: 3