Reputation: 3
While reading some code, I didn't understand the meaning of the const
modifier. For example, are the following two lines equivalent?
void output() const;
const void output();
Upvotes: 0
Views: 191
Reputation: 1262
For any case
const T function(ARGS ...)
means that the function returns const T
object.
For T function(ARGS ...) const
things are different. First, you can't have this kind of function wherever you want. This function must be only as a non-static
member function of user-defined type
(AKA struct
or class
).
class A
{
T foo() const; // const function
const T foo1() const; // wanted to show that you can use both together.
static const T foo2(); // this is another option
static T foo3() const; // error: static function cant be const
static const T foo4() const; // error: the same as above
}
Non-static const
member functions promise, that the object you call the function on, can't be changed.
From the above example
An a;
// here you can call any function on the object a that compiles
const A b;
// here you can call only the functions (for non-static ones) that have the `const` modifier
Also, note, that if you try a member variable in the const
function, you will get a compiler error:
class B
{
int var;
void foo() const {var = 1;} // error: can't modify value
void foo1() {var = 1;} // alright
}
To make it possible to modify a variable in the const function
, you should declare the variable as a mutable
one.
class C
{
mutable int var1;
void foo() {var1 = 1;} // OK
void bar() const {var1 = 1;} // Also OK
}
This might seem to be useless, but the use case is some kind of counters, etc.
Upvotes: 4
Reputation: 438
In void output() const
, const
means that you "promise" the compiler not to modify the member data
of the class using that output()
function. Which means output()
will only be used as a read-only
function.
const void output()
means that the function return
type will be const
ant.
Upvotes: 4