This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 3 years ago.
I got a book, where there is written something like:
class Foo
{
public:
int Bar(int random_arg) const
{
// code
}
};
What does it mean?
A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.
Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this pointer. So a method int Foo::Bar(int random_arg) (without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg), and a call such as Foo f; f.Bar(4) will internally correspond to something like Foo f; Foo_Bar(&f, 4). Now adding the const at the end (int Foo::Bar(int random_arg) const) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg). Since the type of this in such case is const, no modifications of member variables are possible.
It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)
As usual when dealing with the const keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const only applies when adding const to the end of the function declaration after the parenthesis.
const is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword:
Const correctness
The C++ 'const' Declaration: Why & How
Consider two class-typed variables:
class Boo { ... };
Boo b0; // mutable object
const Boo b1; // non-mutable object
Now you are able to call any member function of Boo on b0, but only const-qualified member functions on b1.
Bar is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.
Similar to this question.
In essence it means that the method Bar will not modify non mutable member variables of Foo.
I always find it conceptually easier to think of that you are making the this pointer const (which is pretty much what it does).
Function can't change its parameters via the pointer/reference you gave it.
I go to this page every time I need to think about it:
http://www.parashift.com/c++-faq-lite/const-correctness.html
I believe there's also a good chapter in Meyers' "More Effective C++".
Related
Today I got a problem. I am in the need of a static member function, const is not a must but a better. But, I didn't succeed in my efforts. Can anybody say why or how?
When you apply the const qualifier to a nonstatic member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type C const*, whereas for a member function that is not const-qualified, the this pointer is of type C*.
A static member function does not have a this pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.
I agree with your question, but unfortunately the C++ is designed that way. For example:
class A {
int i; //<--- accessed with 'this'
static int s; //<---- accessed without 'this'
public:
static void foo () const // <-- imaginary const
{}
};
As of today, the const is considered in context of this. In a way, it's narrow. It can be made broader by applying this const beyond this pointer.
i.e. the "proposed" const, which may also apply to static functions, will restrict the static members from any modification.
In the example code, if foo() can be made const, then in that function, A::s cannot be modified. I can't see any language side effects, if this rule is added to standard. On the contrary, it's amusing that why such rule doesn't exist!
It is unfortunate that C++ doesn't accept it as per design but logically there are few use cases in which it validates well.
A function which is class level valid(static) might not change any static data, may be it will just query data should be const.
May be it should be like
if(Object)
MakeThisConstant()
else
MakeStaticDataConstant() // Only in the scope but static data cannot be constant so may be it should in some scenarios
Without getting into the details, it's because there may or may not be an object modified by the function, so const is ambiguous to the compiler.
Recall that const keeps objects constant, but there may or may not be an object here to keep constant.
A 'const member function' is not
allowed to modify the object it is called on, but static member
functions are not called on any object.
It is used directly by scope resolution operator.
Thus having a const static member function makes no sense, hence it is illegal.
Today I got a problem. I am in the need of a static member function, const is not a must but a better. But, I didn't succeed in my efforts. Can anybody say why or how?
When you apply the const qualifier to a nonstatic member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type C const*, whereas for a member function that is not const-qualified, the this pointer is of type C*.
A static member function does not have a this pointer (such a function is not called on a particular instance of a class), so const qualification of a static member function doesn't make any sense.
I agree with your question, but unfortunately the C++ is designed that way. For example:
class A {
int i; //<--- accessed with 'this'
static int s; //<---- accessed without 'this'
public:
static void foo () const // <-- imaginary const
{}
};
As of today, the const is considered in context of this. In a way, it's narrow. It can be made broader by applying this const beyond this pointer.
i.e. the "proposed" const, which may also apply to static functions, will restrict the static members from any modification.
In the example code, if foo() can be made const, then in that function, A::s cannot be modified. I can't see any language side effects, if this rule is added to standard. On the contrary, it's amusing that why such rule doesn't exist!
It is unfortunate that C++ doesn't accept it as per design but logically there are few use cases in which it validates well.
A function which is class level valid(static) might not change any static data, may be it will just query data should be const.
May be it should be like
if(Object)
MakeThisConstant()
else
MakeStaticDataConstant() // Only in the scope but static data cannot be constant so may be it should in some scenarios
Without getting into the details, it's because there may or may not be an object modified by the function, so const is ambiguous to the compiler.
Recall that const keeps objects constant, but there may or may not be an object here to keep constant.
A 'const member function' is not
allowed to modify the object it is called on, but static member
functions are not called on any object.
It is used directly by scope resolution operator.
Thus having a const static member function makes no sense, hence it is illegal.
I am reading some C++ text from the address https://cs.senecac.on.ca/~chris.szalwinski/archives/btp200.081/content/overl.html.
in the first lines, they say:
The signature of a member function consists of:
the function name,
the data types of its parameters,
the order of the parameters and
possibly
the const status of the function.
I don't understand what they mean by saying "the const status of the function".
Can anyone elaborate on that, please?
Thanks.
In C++, you can declare a member function of a class to be const, by appending that keyword to its signature (for instance, int MyClass:doSomething(int param) const {...}). Doing so guarantees that the function won't change the (non-mutable) members of the class object on which the function is called - and hence it can be called with const instances of that class.
It is permissible to have two different member functions for a class whose signature differs only in whether they are declared const or not.
They mean to sum up the items of where functions must differ in order to be put into the same class scope. The const at the end is:
struct A {
void f();
void f() const;
};
These are valid overloads. The first is called if you call f on a A, and the second is used if you call it on a const A:
A a;
a.f(); // takes first
A const& b = a;
b.f(); // takes second
Note that the term "signature" is misused here. The signature of a function is more broad, and includes also the class of which a function is a member of. A signature uniquely identifies a function.
Declaring a member function as const tells the compiler that the member function will not modify the object's data and will not invoke other member functions that are not const.
The compiler will check to make sure that you really don't modify the data. You can call a const member function for either a const or a non-const object, but you can't call a non-const member function for a const object (because it could modify the object).
You can read more about constness in C++ here.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the meaning of a const at end of a member function?
I have seen some classes that have something like this.
void something() const;
What does const means?
In addition to what SRM said (that the function cannot alter any members of the class (which is not exactly true, e.g. in the case of mutable members, which still can be altered)), it means that you can call this member function on things that are const. So if you get a Foo const& foo as a parameter, you can only call members that are declared const like in your question.
It means that something may not modify member variables of the class.
The exception to the rule is if there are member variables declared with the mutable keyword.
For example, suppose you have a std::map< int, int > var member variable and a method that does the following:
int Class::method () const {
if (var.find (42) != var.end ()) {
return var[42];
}
return 0;
}
That will not compile since var[42] modifies var if 42 is not in the container. Declaring var as mutable allows you to pass compilation.
It means the function will not modify any member variables. To be more precise, it means the function cannot alter any non-static or immutable member variables of that class
To be absolutely precise - it makes the implicit this pointer in the function a pointer to a const object.
From 9.2.1 "The this pointer""
The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*.
All the other behaviors (that you can't modify the object members, that you can call the function using a const object, etc) fall from that.
it declares that this function can not change any data. Makes it a Read Only Function.
This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 3 years ago.
I got a book, where there is written something like:
class Foo
{
public:
int Bar(int random_arg) const
{
// code
}
};
What does it mean?
A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.
Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this pointer. So a method int Foo::Bar(int random_arg) (without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg), and a call such as Foo f; f.Bar(4) will internally correspond to something like Foo f; Foo_Bar(&f, 4). Now adding the const at the end (int Foo::Bar(int random_arg) const) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg). Since the type of this in such case is const, no modifications of member variables are possible.
It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)
As usual when dealing with the const keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const only applies when adding const to the end of the function declaration after the parenthesis.
const is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword:
Const correctness
The C++ 'const' Declaration: Why & How
Consider two class-typed variables:
class Boo { ... };
Boo b0; // mutable object
const Boo b1; // non-mutable object
Now you are able to call any member function of Boo on b0, but only const-qualified member functions on b1.
Bar is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.
Similar to this question.
In essence it means that the method Bar will not modify non mutable member variables of Foo.
I always find it conceptually easier to think of that you are making the this pointer const (which is pretty much what it does).
Function can't change its parameters via the pointer/reference you gave it.
I go to this page every time I need to think about it:
http://www.parashift.com/c++-faq-lite/const-correctness.html
I believe there's also a good chapter in Meyers' "More Effective C++".