Benefits of using const functions

D

denis

What are the benefits of using const functions?
How does the compiler interpret const functions?
Thanks, Denis
 
M

matthewlimber

denis said:
What are the benefits of using const functions?
How does the compiler interpret const functions?
Thanks, Denis
From _C++ Coding Standards_ (p. 30, parentheses deleted): "const is
your friend: Immutable values are easier to understand, track, and
reason about, so prefer constants over variables wherever it is
sensible and make const your default choice when you define a value:
It's safe, it's checked at compile time, and it's integrated with C++'s
type system."

The same applies to const member functions, which essentially just make
the "this" pointer const.

See also these FAQs:

http://www.parashift.com/c++-faq-lite/const-correctness.html

Cheers! --M
 
R

roberts.noah

denis said:
What are the benefits of using const functions?
How does the compiler interpret const functions?
Thanks, Denis

Well, you can't call a non-const member on a const object. So if you
want to pass by reference in and out of functions and you want to
advertize that those functions won't change your object then having
objects without const functions become pretty much useless. This is a
major feature of C++ and I recommend becomming familiar with it. I
work on projects where people weren't familiar with const and didn't
use it while building it originally and it becomes a big mess when you
start introducing it in places it belongs.

http://www.linuxjournal.com/article/7629
 
M

marcwentink

What are the benefits of using const functions?

You know what might get changed and what not! About the compiler, I
think const does not have any influence on the object code, in the
sense that it makes the resulting machine code slower (or faster).
 
M

marcwentink

What are the benefits of using const functions?

You know what might get changed and what not! About the compiler, I
think const does not have any influence on the object code, in the
sense that it makes the resulting machine code slower (or faster).
 
T

Tomás

denis posted:
What are the benefits of using const functions?
How does the compiler interpret const functions?
Thanks, Denis


class Monkey
{
private:

unsigned amount_bananas;

public:

void EatBanana()
{
--amount_bananas;
}

void EatBanana() const
{
ThieveBananaFromSomwhere();
}

};


-Tomás
 

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,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top