what does the const mean??

G

gouki

class X {
// members
public:
int foo() const;

}


int X::foo() const // what is the const for???
{

//do something
}
 
P

Peter van Merkerk

gouki said:
class X {
// members
public:
int foo() const;

}


int X::foo() const // what is the const for???
{

//do something
}

It states that the X::foo() function does not modify the "observable"
state of the object. In other words from the callers perspective it
doesn't matter whether someone has called the X::foo() in past or not.
A 'getter' function is a typical example of a const function.

When a member function is declared const, that function cannot change
member variables or call other non-const functions on itself or its
members. An excepion to this rule are 'mutable' members, which may be
modified by a const function. Mutable members are typically used for
caching purposes.
 
T

tom_usenet

It states that the X::foo() function does not modify the "observable"
state of the object. In other words from the callers perspective it
doesn't matter whether someone has called the X::foo() in past or not.
A 'getter' function is a typical example of a const function.

When a member function is declared const, that function cannot change
member variables or call other non-const functions on itself or its
members.

And, importantly, const members can be called on const objects or
through const pointers and references. e.g.

const X& x = ...;
//x.nonconst(); //error
x.constmem(); //fine

Tom
 
R

Refuse to State

Lot's of discussion about implications of the const qualifier on a
method declaration. What it means to the compiler is that the "this"
pointer inside foo is const X*, instead of X*. References to member
functions or data of class X (or it's parent classes) are implicitly
references to this->member.

dag
 

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,172
Messages
2,570,934
Members
47,479
Latest member
JaysonK723

Latest Threads

Top