// contrived, but illustrative sample program
#include <stream.h>
struct sample
{
int variable;
int &value() const;
};
int &sample::value() const // declare the return value as
{ // a const
return variable;
}
main()
{
sample x;
x.variable = 2;
cout << x.variable << '\n'; // prints 2 on my system
x.value() = 3; // should be warning/error, right?
cout << x.variable << '\n'; // prints 3 on my system
}
G++ (v 1.37) compiles this without warning or error. From what I
understand, placing the 'const' keyword after the parameter list of a
function should make the return value a const. Makes sense, right?
So is it something I don't quite understand, or is it G++?
Thanks.
--
Mark M. Lacey [la...@cps.msu.edu]
All reasonable and thoughtful responses are welcome.
[reasonable (adj.) - using or showing reason, or sound judgement; sensible]
[thoughtful (adj.) - full of thought; medatative; thinking]
>I have a question about declaring the return value from a function as
>'const.' Some sample code:
> struct sample
> {
> int variable;
> int &value() const;
> };
[Code deleted...]
> sample x;
> x.value() = 3; // should be warning/error, right?
No, the "const", as you used it, says that calling x.value() does not
change the state of x (such as x.variable). Otherwise, you would not
be allowed to do:
void foo(const sample& x)
{
if (x.value() == 3) // OK only because sample::value() is const
...
To prohibit the assignment, use:
struct sample
{
const int &value();
...
--------------------------------
Matt Mahoney, m...@epg.harris.com
#include <disclaimer.h>
You misunderstand this usage of const. This declares that *this is const,
i.e., that the method sample::value() will not modify the sample on which
it is invoked. If you want to declare the return value to be const, then
use the normal C syntax:
const int &value();
===========================================================================
Josh Mittleman (mit...@watson.ibm.com or jos...@paul.rutgers.edu)
J2-C28 T.J. Watson Research Center, PO Box 704, Yorktown Heights, NY 10598
The declaration int &value() const; says that calling the function
value() won't modify the underlying class. To return a reference that isn't
modifiable, you need to declare the data pointed to by the reference const
as well:
const int & value() const;
It's you. const after a member-function declaration means "this member
will not change its object. To make the return value a const use
const int &sample::value() ;
>All reasonable and thoughtful responses are welcome.
>[reasonable (adj.) - using or showing reason, or sound judgement; sensible]
>[thoughtful (adj.) - full of thought; medatative; thinking]
- Michael Lorton ...
... who is not creative enough to write a .sig