Const with function

What is the difference between 'const' before and after function name in the code below:
1
2
3
4
5
6
7
8
9
10
11
const int foo() // const before
{
   return 1;
}

int main()
{
    int a = foo();
    a = 2; // a can be changed
    return 0;
}

And how about const after function name?
Thanks for your help.
const after a function name applies to a struct/class function and means that the member function can only change mutable class/struct variables.

const before depends upon what the type is.

For a pointer (*), it means that the pointer is to const data (ie the data pointed to can't be changed).

For a ref (&) it means the data can't be changed.

For the rest it has no effect as it's value assigned.
Thanks for your reply.
So, is 'const int foo();' the same with ’int foo();'?
> const int foo() // const before

The const qualifier on the returned scalar type (int) is ignored.
https://coliru.stacked-crooked.com/a/afbeb4ff082c7b57
(The const qualifier has no effect; we can't modify a prvalue of type int)


> a = 2; // a can be changed

The type of a is a modifiable (non-const) int; it was initialised with the prvalue foo()


> And how about const after function name?

See: https://isocpp.org/wiki/faq/const-correctness#const-member-fns
Last edited on
Thanks for all your reply.
I get it.
I guess I must have misread the question because I ended up answering what difference it is between using const inside the parameter list compared to using it after.

If you're writing a function that should modify a class object you can either write it as a "member function" (inside the class) or as a "free function" (outside the class).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

struct S
{
	int x;
	
	// member function
	void foo()
	{
		x = 5;
	}
};

// free function
void foo(S& s)
{
	s.x = 5;
}

int main()
{
	S s;
	s.foo(); // calls the member function
	foo(s); // calls the free function
}

These two functions named "foo" are more or less identical if we ignore the syntactical difference. The object is essentially "passed" to the member function using an implicit this parameter.


Now, what if we want to write a function "bar" that does not modify the object, and that can be used with objects declared as const?

With a free function it's easy, just mark the parameter reference as const.
1
2
3
4
void bar(const S& s)
{
	std::cout << s.x << "\n";
}

But how do we do it with a member function? The answer is that we write const after the function's parameter list.
1
2
3
4
5
6
7
8
9
struct S
{
	...
	
	void bar() const
	{
		std::cout << x << "\n";
	}
};

Last edited on
Topic archived. No new replies allowed.