Reputation: 69
In my attempt to teach myself C++, I was hoping to get some help in how to read the const-ness of a expression/function etc. For example, the code below:
const screen &display(std::ostream &output) const {
do_display(output); return *this;
}
In the above code. there are two const
declarations in the function display
. In "English" how is that properly read? example: the first const
is a const
to reference or const
to type screen
? etc. and what exactly does the const
-ness mean/imply when a reference is const etc. I have tried reading up on it but is still a bit muddy at this point.
Feel free to point to a youtube video or other reference material. Hopefully the material that is very clear.
Upvotes: 0
Views: 64
Reputation:
Read it right to left.
int const & foo() const
const
method which returns a...
int const & foo() const
Reference to a...
int const & foo() const
const int
.
The const
can go on either side of int
. You can read it as a "constant integer" or a "integer which is constant".
Upvotes: 1
Reputation: 3430
You read it right to left. You have a constant method that returns a reference to a screen that is constant.
Returning a constant reference means you cannot modify what is returned. If you call the method and assign it to some variable, the variable must use the const keyword. The only exception to this is if you cast the returned reference from the method to something that is not constant.
Here's a helpful link for more detail on the right to left rule: http://ieng9.ucsd.edu/~cs30x/rt_lt.rule.html
That's actually written by a professor at UCSD (and he's pretty good).
The const on the right side of the method just means you can't modify any instance variables inside the function (for the most part). There's a bit more to it, but for more detail, refer to: Meaning of "const" last in a C++ method declaration?
Upvotes: 1
Reputation: 224904
I've always found that the simplest way to remember it is:
const
applies to whatever is to the left of it, unless there isn't anything to the left of it, in which case it applies to whatever is to the right of it.
So, you have a const
method that returns a const
reference to a screen
.
A const
reference means you can't modify the referenced object. The const
method means that the method won't modify the object it's being called on (the this
pointer inside that method will be to a const
object).
Upvotes: 3
Reputation: 118330
In English it means:
display()
is a constant method of its class (this is the 2nd const
keyword) that takes a reference to a std::ostream
class instance as its parameter, and returns a reference to a constant (this is the 1st const
keyword) instance of the screen
class.
A const
reference means that this reference cannot be used to modify the object being referenced. You can use the reference only to access, but not change, the members of the class, or to invoke the class's const
methods (like display
() is a const
method of its own class).
Upvotes: 0