The meaning of "const" in a function declaration [duplicate] - c++

This question already has answers here:
Const correctness: const char const * const GetName const (//stuff);
(8 answers)
Closed 8 years ago.
I have a function with 3 const's in it:
const std::string at(const unsigned int index) const;
To my understanding, the parameter (const unsigned int index ) means that index will not be changed. What about the other two const's? Why are they there?

The const keywoard in C++ indicates that a particular object or variable is not modifiable. It can be used in various contexts:
Const variables
Declaring a variable as const inside of a function indicates that the variable will not be modified inside the function.
Const member functions
Declaring a member function as const, which is done by appending const to the end of the function prototype, indicates that the function is a "read-only" function that does not modify the object for which it is called.
The rule for const viability is that const-ness can be applied to a non-const variable or member function, but once applied it cannot be removed.

The first const says that the return type is const, the second const says the parameter is const, and the third const says that the function is a const function...
This question is actually a duplicate... follow this link
C++ Const Usage Explanation

const std::string at(const unsigned int index) const;
in this example, the first const from left side is a constant for return type, which means whatever value it will return that can be saved in a const variable only (even type casting is possible which will change the property of data).
second const as you said it is correct.
third const says that the function is constant function. that means inside that function you are not modifying any variables which will change the state of objects.
if you are modifying any class or global variable inside const function then compiler will throw error.

Related

Difference between Const usage in functions in c++

I'm having the below method with multiple const keywords. why are they used?
const int* MyClass::getvalue(const int input) const
if returning a pointer from a method, what are the ways to restrict the user from changing the pointer value and pointer itself?
First of all, having the return type for a value (as opposed to a reference or a pointer) being const is rather useless. The caller of the function can still copy the value to a non-constant variable anyway. For a reference or a pointer, it means that the referenced/pointed to object can not be modified. It can still be copied to a non-constant object though.
The argument being const means that the function can not change the argument. It is partly informational, partly helps the compiler choose optimizations, and for references or pointers means that whatever is referenced/pointed to can't be modified. For references there's also the semantic that you can pass temporary objects to the function.
The last const is for the function itself, and makes it so that the function can only be called on const objects. If you have a non-const MyClass object, this function can't be called on it. This const is part of the function signature, together with the function name and its argument types. That means you can have two overloaded functions with the same name and arguments, one being const qualified and one not.
I'm having the below method with multiple const keywords. why are they used?
const int MyClass::getvalue(const int input) const
^
This makes the return value const. There is no reason to use a return by const value. Some compilers will warn if you use const here. Note that conversely, a reference or a pointer to const object would be reasonable.
const int MyClass::getvalue(const int input) const
^
This makes the argument const. Whether a value argument is const or not makes little difference. A minor advantage of const is that you can know from the declaration that the local object won't change throughout the function, which can be helpful if the function is complex.
const int MyClass::getvalue(const int input) const
^
This makes a member function const. This allows the member function to be called on const instances of the class, but also prevents the function from modifying non-mutable members of the object.
if returning a pointer from a method, what are the ways to restrict the user from changing the pointer value and pointer itself?
There is no way of restricting the user from changing the value of a pointer object that you've returned to them, and there is never a need to do so.
You can restrict the user from modifying the pointed object by returning a pointer to const.
The last const specifies that getvalue() won't change the instance of MyClass it is called upon.
const int input declares a parameter of type int to the function getvalue() specified as const. Its value cannot be changed inside the function.
In the return type const is quite meaningless since the returned value can be assigned to a non-const-qualified int without problem.
what are the ways to restrict the user from changing the pointer value and pointer itself?
Read declarations backwards:
int const * const foo; // foo is a constant pointer to a constant int
int * const bar; // bar is a constant pointer to a int
int const * qux; // qux is a pointer to a constant int

How do read this C++ statement

I'm currently going through C++ primer Plus by Prata and came across this statement regarding *this pointer:
const Stock &topval(const Stock &s) const;
Giving that Stock is a class and topval a function ,
How do you read this statement?
I tried using the clockwise/spiral approach but I get confused by all the const.
I believe that understand how to read it will allow me to better understand the concept that it is trying to prove.
Thanks!
topval( ) // topval is a member function...
const; // In which *this is const...
const Stock &s // Taking in a reference
// to a const Stock...
const Stock & // And returning a reference
// to a const Stock.
It's a function that both takes and returns a reference to a const Stock (not necessarily the same one, to be clear), and does not mutate this when it does so.
It declares a member function (because of the last const) which:
Named topval
Do not change any other member of the class, see the last const
Takes only one parameter: const Stock& s
Returns a value of type const Stock&
It'd be a lot easier if people wrote this code sensibly:
const Stock& topval(const Stock& s) const;
topval is a const function, taking a const Stock& called s, and returning a const Stock&.
Simple!
The const in the end is applied to the this pointer . The const in the argument is applied to the argument, and the const in the first part of the sentence to the return value.
simplified syntax explanation
Return value - function name - ( argument list ) - const modifier.
The const specifier is a function modifier specifying that the pointer passed to this function is const, therefore you cannot modify member variables , except those declared mutable in the class definition.
The elaborate syntax is :
noptr-declarator ( parameter-list ) cv(optional) ref(optional) except(optional) attr(optional) -> trailing require
Therefore you declare a method That
Returns a const reference to a Stock after having received as input a const reference to a Stock object , and this pointer is a const pointer for this method being called.
The not so used but equivalent and arguable proper way to write this is
Stock const &topval( Stock const &s) const;
That now permits to spot where the cv-qualifier is actually applied (i.e. to the left-of the qualifier )
const Stock &topval( const Stock &s) const;
So you're declaring a function topval, that returns the memory address for an object of the type Stock as const. The function topval takes as an argument the memory address of Stock object. Since this is const, you will not be able to change this object inside topval.
Finally const at the end means, that this function (topval) will not be able to change any members of the class Stock..
I think it's more or less this meaning, it's been a while without c++

What does the const keyword do in an operator definition?

I don't understand what the const keyword is used for in front of the return type and after the parameter list of this operator definition. This is taken from an example from a book.
const char& operator [] (int num) const
{
if (num < getlength())
return Buffer[num];
}
The C++ const keyword basically means "something cannot change, or cannot delegate operations that change onto other entities." This refers to a specific variable: either an arbitrary variable declaration, or implicitly to this in a member function.
The const before the function name is part of the return type:
const char&
This is a reference to a const char, meaning it is not possible to assign a new value to it:
foo[2] = 'q'; // error
The const at the end of the function definition means "this function cannot change this object and cannot call non-const functions on any object." In other words, invoking this function cannot change any state.
const char& operator [] (int num) const {
this->modifySomething(); // error
Buffer.modifySomething(); // error
return Buffer[num];
}
The goal of const-correctness is a big topic, but the short version is being able to guarantee that immutable state actually is immutable. This helps with thread safety and helps the compiler optimize your code.
It means the actual object you are calling this method on will not change, and if you attempt to change it, you'll get a compiler error.

A few questions about const methods in my class [duplicate]

This question already has answers here:
C++ Const Usage Explanation
(12 answers)
Closed 7 years ago.
I'm new to using C++ to write enterprise software at my company and the usage of const in member functions has been quite confusing to me. For example, I have the following method:
string DAC::impulse_find(int i)
There will be no modification of the variable i. My code compiles perfectly when I use these three variants of adding const to the above method:
const string DAC::impulse_find(const int i) const
const string const DAC::impulse_find(const int i) const
string const DAC::impulse_find(const int i) const
So what exactly is the difference between these three? I looked at some past answers and say "It applies to whatever is to the left" but that is still confusing. Does it apply to anything, such as the name of the class as well?
There is no difference between
const std::string
std::string const
The order of const is irrelevant since you are not dealing with pointers.
Having many const as a qualifier doesn't make sense. Did you turn up the warning level on your compiler to maximum?
Edit 1: Pointers and Const
Since you are returning a copy of a variable the effectiveness of const is worthless. The original item from the function can't be modified because you are returning a copy.
Maybe you are confused with the pointer syntax, where the placement of const matters:
string const * const -- constant pointer to a constant (read-only string). Pointer cannot be modified.
string const * -- Mutable pointer to a constant (read-only) string. Pointer value can change.
string * const -- Constant pointer to a read/write string. Pointer value cannot be changed.
string * -- Mutable pointer to a read/write string. Pointer value can be changed.
The const for read-only data may be placed before or after the type:
const string *
string const *
Both of the above are equivalent.
All three version
const string …
const string const …
string const …
are identical.
The placement of const doesn't matter here. The duplicate const in the second version is redundant and your compiler should give a warning about it.
Moreover, the consts don't make sense here because the string is returned as a copy. Returning a const value brings you nothing (see KABoissonneault's comment), only references or pointers to const make sense as a return type.

C++ Difference between const positioning

I'm struggling to get my head around the differences between the various places you can put 'const' on a function declaration in c++.
What is the difference between const at the beginning:
const int MyClass::showName(string id){
...
}
And const at the end like:
int MyClass::showName(string id) const{
...
}
Also, what is the result of having const both at the beginning and at the end like this:
const int MyClass::showName(string id) const{
...
}
const int MyClass::showName(string id) returns a const int object. So the calling code can not change the returned int. If the calling code is like const int a = m.showName("id"); a = 10; then it will be marked as a compiler error. However, as noted by #David Heffernan below, since the integer is returned by copy the calling code is not obliged to use const int. It can very well declare int as the return type and modify it. Since the object is returned by copy, it doesn't make much sense to declare the return type as const int.
int MyClass::showName(string id) const tells that the method showName is a const member function. A const member function is the one which does not modify any member variables of the class (unless they are marked as mutable). So if you have member variable int m_a in class MyClass and if you try to do m_a = 10; inside showName you will get a compiler error.
Third is the combination of the above two cases.
The const attached to the return value applies to the return value. Since the return value is copied it's a pointless declaration and it makes no difference whether or not you include it.
The const after the parameter list means that the function does not modify any state of the object that is not marked as mutable. This is a const member function and if you have a const object the compiler will not allow you to call non-const member functions on a const object.
There is no interaction between these two uses of const - they are completely independent constructs
The difference is that the const applies to different things.
This says that showName returns a constant int value -- one that is immutable. Of course since the int is returned by value the presence of const here does not play any role.
const int MyClass::showName(string id)
And this says that showName does not modify the observable state of MyClass (technically: it does not modify any member that is not declared mutable), and therefore you are allowed to call it on a value of type const MyClass.
int MyClass::showName(string id) const
If you use both consts then both of the above apply.
Questions like this tend to strengthen my resolve to follow the advice of Dan Saks as outlined in this "Conversations with a Guru" article: http://www.drdobbs.com/conversationsa-midsummer-nights-madness/184403835 .
In particular it deals with how the placement of const changes things. (*) I realize that I am extremely unlikely to convert anyone from writing const int ... to int const ..., but that said, there is one reason I prefer to do the latter.
(*) incuding a note that swapping the const with the type declaration at the very start is the one change that has no effect.
It makes for very easy readability, because for any instance of the word
const in a declaration, everything to the left of it is the type of what is const, and everything to the right is what actually is const.
Consider a declaration like:
int const * * const pointerToPointer;
The first const states that the integers at the end of the pointer chain are const, and they are to be found at * * const pointerToPointer. Meanwhile the second one states that an object of type pointer to pointer to const int is also const and that this object is pointerToPointer.
In the OP's case:
int const MyClass::showName(string id){
...
}
The type of what is const is int, and what is const is the return value from the function.
Meanwhile:
int MyClass::showName(string id) const {
...
}
Here the type of what is const is function(string) returning int, and what is const is the function itself, i.e. the function body.