3

newbie here!

I am reading a code and I see the author frequently writing a member function as

const int func (const scalar& a) const
// etc

You see there are three const here, now I understand the middle one, const scalar& a, that aims to not change the object a, but what about the other two const?

Is it a good habit that I should do this all the time, to protect blahblah unchanged?

Thanks a lot!

Daniel
  • 2,576
  • 7
  • 37
  • 51

2 Answers2

7

The code you posted is not valid, it will not compile. However, if you consider

class MyClass {
  const int& func (const scalar& a) const {
    // ...
  }
};

The first const will specify that the return value is constant (i.e. immutable). The second const (const scalar& a) specifies that the function does not modify the value of the value of the argument a. The third const specifies that func is a constant member function, i.e. it does not modify the MyClass instance itself.

Krumelur
  • 31,081
  • 7
  • 77
  • 119
  • 1
    The key takeaway here is that each `const` is modifying a different part of the declaration, and each has a purpose. – Mark Ransom May 29 '12 at 22:53
  • 3
    Here's more fun! `constexpr const char* const& func(const char* const& a) const` – Mooing Duck May 29 '12 at 22:58
  • `constexpr const char* const& func(const char* const& a) const`, what? – Daniel May 29 '12 at 23:06
  • @Daniel That one is basically the same explanation except with `char* const` instead of `int` for the type and the C++11 `constexpr` keyword to also guarantee to the compiler that function is a compile-time constant ;-) – AJG85 May 29 '12 at 23:56
0

Since nobody has mentioned it yet: there is absolutely no difference between

const int some_function();

and

int some_function();

The const on scalar return types (such as int) is ignored; it only matters for class types. related

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662