user13232081
user13232081

Reputation:

Why is const redundant when using const functions C++?

So all modifiers that I have come across in C++ have came prior to the name of the function. Why is const different? Why must it both precede the name and come prior to the function block?

const int getSize() const;

or

const int getSize const {
...
}

Upvotes: 1

Views: 264

Answers (2)

cigien
cigien

Reputation: 60208

These are 2 different usages of the const keyword.

In this case:

const int getSize() { 

the function is returning an int that is const, i.e. the return value cannot be modified. This is not very useful, since the const in the return value is going to be ignored (compilers will warn about this). const in the return type is only useful when returning a const*, or a const&.

In this case:

int getSize() const { 

this is a const-qualified member function, i.e. this member function can be called on const objects. Also, this guarantees that the object will not be modified, even if it's non-const.

Of course, you can use both of these together:

const int getSize() const { 

which is a const-qualified member function that returns a const int.

Upvotes: 4

afic
afic

Reputation: 510

The const before the function is applied to the return type of the function. The const after is only for member functions and means that the member function is callable on a const object.

As a note returning a const int does not make sense, many compilers will warn that the const gets discarded.

Upvotes: 1

Related Questions