I have a function
const std::string& getRecordingJobToken() { return getToken(); }
const std::string& getToken() const { return m_Token; }
std::string m_Token;
I am able to call it as below
const std::string jobToken = getRecordingJobToken();
However when I do this,
const std::string jobToken;
jobToken = getRecordingJobToken();
It throws me this error –
error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive]
What is the difference ?
I know that a reference variable has to be initialized immediately.
std::string &ref = a;
Is it some similiar logic ? The reason i am confused is that though getRecordingJobToken() returns a const reference, the variable jobToken that I have is not a reference variable. It is a variable that is used to take a string reference being returned from the getRecordingJobToken() function.
>Solution :
Initialization and assignment are different things. jobToken is const, it could (and must) be initialized, e.g.
const std::string jobToken = getRecordingJobToken(); // copy-initialization
but can’t be assigned (modified) later, e.g.
const std::string jobToken; // default-initialization
jobToken = getRecordingJobToken(); // fails; assignment