const after function name

R

Robert

Hi all,

class Homer {
public:
int dot(int) const {return 1;}
...
}

what's the meaning of const after function name?

Best regards,
Robert
 
G

gevadas

Const at the end of function tells the compiler that your function wont
modify any private variables of the class.You can only use these
functions with const objects.

Gevadas A. Akkara
 
D

Dom Gilligan

Hi all,

class Homer {
public:
int dot(int) const {return 1;}
...
}

what's the meaning of const after function name?

Best regards,
Robert

'dot' doesn't modify anything in 'Homer'. You'll get warned if you do
try to modify something. Not necessary, but may enable optimisation.

Dom
 
C

Christian Meier

Const at the end of function tells the compiler that your function wont
modify any private variables of the class.You can only use these
functions with const objects.

Gevadas A. Akkara

Not only private members.
const after function name makes the this-pointer const. So you are not
allowed to change a member variable in this function.

Greetings Chris
 
E

Earl Purple

You won't "warned" you'll get a compiler error.
A const function is also not allowed to:
- Call a non-const member function
- Return by reference any member variable (other than by
const-reference).

A const function may return a member pointer (to non-const).
 
F

Frank Chang

How about mutable member variables, can they be modified in const
member functions?
 
J

Jaspreet

Frank said:
How about mutable member variables, can they be modified in const
member functions?

Yes they are the 'only' kind of data members that can be modified in a
const member function.
 
J

Jack Klein

Not only private members.
const after function name makes the this-pointer const. So you are not
allowed to change a member variable in this function.

I hope you mean:

The const keyword after a member function name makes the object *this
constant inside the function.

'this' itself is always constant.
 

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,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top