Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding const reference returned from a function

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading