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++
Related
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
I'm trying to understand and achieve const correctness on a Tetris Project.
Here is a recurrent problem that i have when i'm trying to add const where I think it's necessary.
I have a (Piece) class, and one of it's class private member is
Point rotationCenter;
And I'm trying to write a getter like this:
inline Point & Piece::getRotationCenter() const
{
return rotationCenter;
}
Before, I had the same getter, but not as a const function, and was working. Now, I got the C2240 error "impossible to convert const Point to Point &".
What should I do to correct this? Should I leave getRotationCenter without const ?
PS : I read https://isocpp.org/wiki/faq/const-correctness as tutorial.
Why is it impossible to convert const X to X &?
Because if it is allowed, the following dangerous code becomes valid:
const int x = 0;
int& rx = x; // bind const variable to reference (to non-const)
rx = 99; // oops, try to modify the const variable via the reference
What should I do to correct this? Should I leave getRotationCenter without const ?
It depends on your intent. If the returned object could be modified, then make the member function non-const and return Point&. If not, then leave the member function const and make the return type const Point&. A const member function means a promise that won't modify (or provide the possibility to modify) the object (and its members).
Inside const member functions all of the classes data members are const. You cannot bind a non-const reference to your const member data, so you get a compiler error.
If you don't want your caller to modify rotationCenter, then you can return by Point or const Point&.
inline const Point & Piece::getRotationCenter() const
{
return rotationCenter;
}
If you do want the caller to modify rotationCenter (which I would generally not recommend), write two overloads: one which returns by Point& and one which returns by const Point& depending on the qualification of the object you call it on:
inline Point & Piece::getRotationCenter() //not const
{
return rotationCenter;
}
inline const Point & Piece::getRotationCenter() const
{
return rotationCenter;
}
http://cplusplus.com/reference/string/basic_string/operator[]
I understand that it's advantageous to have a second version which returns const to prevent warnings when a const result is required and to mitigate casting but if the function already provides a non-const method (method-- not result) then what is the point of declaring the const-result method const?
You need to understand, that the second (const) version not only returns a different result but is also marked itself as const (this is the second const at the end of the declaration):
const_reference operator[] (size_type pos) const;
These are two different things: The const return value by itself would not be needed in the presence of a non-const method (since the non-const return value can always be casted tò the const version).
But not having a const-version of the operator would mean, that you couldn't use it on const string objects.
The const result is just a result of the constness of the operator itself: if you have a const string and use the operator to get a reference to a single character, clearly this reference must also be const (if not, you could change single characters within a const string).
Assume you have
const std::string str{"test"};
std::cout << str[2];
If you don't have a const member function, the code above will fail, as the this pointer passed implicitly to operator[] is const.
If you have a const std::basic_string you cannot call (non-const) std::basic_string::operator[], as it is, well, not marked const.
If there wasn't a const version of the function, the function could not be invoked on a const instance. For example:
void func (const std::string &h)
{
if (h[0] == "hello")
...
}
How would this work if there wasn't a const version of operator[]?
The const method returns a different type, it returns a const-qualified reference. This means if the const method is used, the result of the method is const-qualified (and therefore is “immutable”). The non-const-qualified method returns a regular reference, which is “mutable”.
You can't have just the const method or else you can't modify individual characters in non-const-qualified std::basic_string objects. And you can't have just the non-const method or you won't be able to call the method on const-qualifed std::basic_string objects.
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.
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.