const follow the member function

A

avier

Hello,

I was reading the C++ codes and was confused by the following:

double expect (double t, double x, double dt) const {

return x + t*dt;

}

Does the "const" in the member function follow the function name mean
the returned double cannot be modified?

Rookie question, thanks for your help in advance.
 
S

Stu

avier said:
Hello,

I was reading the C++ codes and was confused by the following:

double expect (double t, double x, double dt) const {

return x + t*dt;

}

Does the "const" in the member function follow the function name mean
the returned double cannot be modified?

Rookie question, thanks for your help in advance.

It means that the member function does not modify the class object it is a
member of.

Stu
 
A

avier

hi stu,

thanks for the prompt help.

Does it mean that the data in the object will not be modified?
 
M

Maxim Yegorushkin

avier said:
hi stu,

thanks for the prompt help.

Does it mean that the data in the object will not be modified?

It does not.

const for member function is just a hint to the reader that the
function does not change logical state of an object, although object's
physical state (the bits it's comprised of) may well change.
 
J

John Carson

Maxim Yegorushkin said:
It does not.

const for member function is just a hint to the reader that the
function does not change logical state of an object, although object's
physical state (the bits it's comprised of) may well change.

It is far more than a hint.

1. It is a promise that the function won't modify the object's data unless
that data is declared mutable --- a promise that the compiler will enforce.
2. It is a required promise for any function that is called on a const
object --- a requirement that, once again, the compiler will enforce.

For 1., observe that the following won't compile because Set changes the
object in spite of promising not to:

class Test
{
int x;
public:
Test() : x(0)
{}
void Set(int x_) const
{
x = x_; // won't compile; violates the const promise
}
};

For 2., observe that the following won't compile because of the absence of
the const qualifier on the DoNothing function, i.e., the fact that the
DoNothing function does nothing is insufficient; it must declare this fact
with the const keyword:

class Test
{
public:
Test()
{}
void DoNothing()
{}
};

int main()
{
const Test t;
t.DoNothing(); //won't compile; t is declared const but DoNothing isn't
return 0;
}
 

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,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top