const?

J

Justin Robinson

Hi,

What does const mean when it appears at the _end_ of a function signature,
like this:

int f() const
{
return 50;
}

Is it the same if I put it in front like this:

const int f()
{
return 50;
}

Justin
 
M

Mike Wahler

Justin Robinson said:
Hi,

What does const mean when it appears at the _end_ of a function signature,
like this:

int f() const
{
return 50;
}

This syntax is only valid for a member function.
It means that the function will not modify the
object for which it was invoked.
Is it the same if I put it in front like this:

const int f()
{
return 50;
}

No.

Which C++ book(s) are you reading?

-Mike
 
R

Ron Natalie

Mike said:
This syntax is only valid for a member function.
It means that the function will not modify the
object for which it was invoked.

And in turn it means that it is OK to call it on a const object
(and that the this pointer refers to a const object).

This is important for not only does it mean that you are prohibited
from attempting to change the object inside the const method, that
this will be selected when another non-const overload is present

struct S {
void f() const;
void f();
void g();
void h() const;
};

S o;
o.f(); // calls nonconst f()
o.g(); // ok
o.h(); // ok
const S co;
co.f(); // calls const f()
co.g(); // ill-formed! can't call non-const method on const object.
co.h(); // ok
 

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

Forum statistics

Threads
474,183
Messages
2,570,970
Members
47,526
Latest member
RoslynDavi

Latest Threads

Top