Skip to contentSkip to conversation

operator! and lvalue

DISCUSSION Shriramana Sharma 2 participants 2 messages Jun 27, 2007 – Jun 28, 2007

lore
Share & tools
lore
#0 lore raw

In Thinking in C++ chapter on overloading operators, Bruce Eckel gives the following code:

For a non-member operator:

int operator!(const Integer& a) {
cout << "!Integer\n";
return !a.i;
}

For a member operator:

Byte operator!() const {
cout << "!Byte\n";
return Byte(!b);
}

My question is: why is there no "const" before Integer and Byte at the head of the function? There's all that stuff about when temporaries are returned they are automatically const, but throughout the examples in this chapter, only operator! is not explicitly specified to have a const return value whereas in all other relevant cases we have the "const" specified explicitly.

Shriramana Sharma.

#1 lore raw
Quoted 12 lines · Shriramana Sharma

In Thinking in C++ chapter on overloading operators, Bruce Eckel gives the following code:

For a non-member operator:

int operator!(const Integer& a) {
   cout << "!Integer\n";
   return !a.i;
}

For a member operator:

Quoted 7 lines
Byte operator!() const {
   cout << "!Byte\n";
   return Byte(!b);
}

My question is: why is there no "const" before Integer and Byte at the head of the function?

Huh? The only "Integer" which isn't preceded by "const" is in the string literal.

Quoted 5 lines

There's all that stuff about when temporaries are
returned they are automatically const, but throughout the examples in this chapter, only operator! is not explicitly specified to have a const return value whereas in all other relevant cases we have the "const" specified explicitly.

Why would you want to make the return value "const"?

The situation is different if you're referring a reference or pointer, but there's no point in making a copied value "const".

BTW, this list is specifically about C programming on Linux; generic C/C++ questions aren't really on-topic here. The comp.lang.c and comp.lang.c++ newsgroups (and their *.moderated counterparts) might be better places to ask such questions; certainly, they are likely to have many more active users.

Signature · 1 line
Glynn Clements <[email protected]>