const class reference return from function, what does const do?

J

Jim Langston

I'm a little confused. I have a class function declared like:

const CItem& operator << (const std::string &sIn);

Which I use like this:

CItem Item;
Item << "blaster01,1,0,...,0,0,20,0,0,20,eol";

At the end of the method it does:
return *this;

My question is, is my const on the return value doing anything? I don't
know why I even have it there (maybe I copied this method from some source).

const CItem& seems to be to define a reference to a CItem that is constant.
Is that correct? Item is not declared as const, however. Maybe with the
way I'm using this thing I don't need to return any value at all anyway?
 
J

Jim Langston

Rolf Magnus said:
Well, you won't be able to chain the operator calls, like:

Item << "Hello, " << "world";

Basically, returning the reference at all doesn't make much sense if it's
const.


Yes.

Okay, so this begs the question, should I even be overriding the operator <<
anyway? If I'm not returning anything, maybe it would be better to just
make a function like

void LoadFromString( const std::string& sIn )
 
R

Rolf Magnus

Jim said:
I'm a little confused. I have a class function declared like:

const CItem& operator << (const std::string &sIn);

Which I use like this:

CItem Item;
Item << "blaster01,1,0,...,0,0,20,0,0,20,eol";

At the end of the method it does:
return *this;

My question is, is my const on the return value doing anything?

Well, you won't be able to chain the operator calls, like:

Item << "Hello, " << "world";

Basically, returning the reference at all doesn't make much sense if it's
const.
I don't know why I even have it there (maybe I copied this method from
some source).

const CItem& seems to be to define a reference to a CItem that is
constant.
Is that correct?

Yes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top