What does `const` behind a function header mean? [duplicate] - c++

This question already has answers here:
What is the meaning of a const at end of a member function? [duplicate]
(3 answers)
Closed 6 years ago.
There is a class A and it has the following operator() implementation:
void A::operator()(...parameters...) const
{
// operator body
}
What does this const mean?

Methods in C++ can be marked as const like in the above example to indicate that the function does not modify the instance. To enforce this, the this pointer is of type const A* const within the method.
Normally, the this pointer within a method is A* const to indicate that we cannot change what this points to. That is, so that we cannot do this = new A().
But when the type is const A* const we also cannot change any of the properties.

That the method uses this as a const A* and then can only call other const methods.
See this entry of the CPP FAQ.

As already amply described, it means that the method will not modify the observable state of the object. But also, and very importantly, it means the method can be called on a const object, pointer, or reference - a non-const method cannot. ie:
class A
{
public:
void Method1() const
{
}
void Method2()
{
}
};
int main( int /*argc*/, char * /*argv*/ )
{
const A a;
a.Method1(); //ok.
a.Method2(); //compiler error!
return 0;
}

const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called.

It means that calling the operator will not change state of the object.

A const member function promises to not change the observable state of the object.
Under the hood, it might still change state, e.g. of mutable members. However, mutable members should never be visible from anywhere outside the class' interface, i.e. you should never attempt to lie to client code, because client code may validly expect that const functions don't tweak the object's outer hull. Think of mutable as an optimization tool (e.g. for caching and memoization).
Example for mutability:
You have a quadtree class. Under the hood, the quadtree is build up lazily, i.e. on demand; this lazyness is hidden from users of the class. Now, a query-method on that quadtree should be const, because querying a quadtree is expected to not change the quadtree. How do you implement const-correctness and lazyness without breaking C++' rules? Use mutable. Now you have a quadtree that for the user looks const, but you know that under the hood, there's still a lot of change:
class Quadtree {
public:
Quadtree (int depth);
Foo query (Bar which) const;
private:
mutable Node node_;
};

Related

Sorting vector of objects with respect to std::variant field [duplicate]

i'm trying to understand class getters and setters functions...
My question is:
If i design a function that just only get a state from its class (a "getter" function), why mark it as "const member function"?
I mean, why use a const member function if my function is designed to not change any proprieties of its class?
i don't understand please :(
for example:
int GetValue() {return a_private_variable;}
and
int GetValue() const {return a_private_variable;}
what is the real difference?
When you declare a member function as const, like in
int GetValue() const;
then you tell the compiler that it will not modify anything in the object.
That also means you can call the member function on constant object. If you don't have the const modifier then you can't call it on an object that has been defined as const. You can still call const member functions on non-constant objects.
Also note that the const modifier is part of the member function signature, which means you can overload it with a non-const function. That is you can have
int GetValue() const;
int GetValue();
in the same class.
const can show up in three different places in C++.
Example 1:
const Object obj1;
obj1 is a const object. Meaning that you can not change anything on this object. This object can only call const member functions like
int GetValue() const {return a_private_variable;}
Example 2:
int myMethod() const {//do something}
This is a const method. It would be a const member function if it is declared inside of a class. These are the types of methods that const variables can call.
Example 3:
int myMethod(const Object &x) {//do something with x}
This is a method that takes a const parameter. This means that the logic inside myMethod is not allowed to change anything to do with x. Also note the parameter is being passed by reference not by copy. I like to think of this as a read only type of method.
When you are developing software that will be used by others; it is a good idea to not let them break things they don't know they should not break. In this case you can constrain variables, methods, and parameters to be const to guaranteed that the contract is upheld. I tried to summarize the main ideas I learned in college, but there are many resources online around const in C++. Check out this link if you would like to know more. Also it is possible that I remembered somethings incorrectly as I have not been in the C/C++ realm for a while.
A const instance of a class can only call const functions.
Having a const instance of a class is useful for making your programs more stable since then you can't modify the instance by accident.
In your case the functions do exactly the same thing, but it doesn't have to be that way.

Keyword 'const' on functions imply a full read-only of the object fields?

Having the following object
class Parser
{
public:
Parser(ComponentFactory * const factory): _factory(factory) {};
~Parser() = default;
void parse() const {
_factory->setFoo("foo");
}
private:
Factory * _factory;
};
My function parse() is specified as const. That's to say the function shouldn't modify the current object state and performs only read-only logics.
However, does the modification of the factory object imply a change of my current object's state? In other therms, is this even compilable?
I would like to understand why if yes, since I can't find any related subject on the net..
EDIT:
Since none can understand this, let me try to explain it better. In simple words, is the above code supposed to compile?
However, does the modification of the factory object imply a change of my current object's state?
No
In other therms, is this even compilable?
Yes.
I would like to understand why if yes, since I can't find any related subject on the net..
Say you have
struct Foo
{
int* ptr;
Foo() : ptr(new int(0)) {}
// It is valid since it does not change the state of Foo.
// It does not change where ptr points to. It just changes
// the value of what ptr points to.
void set(int value) const { *ptr = value; }
};
The compiler gives you the basic const characteristics. Higher level const-ness needs to be implemented by classes themselves.
In the case of Foo, if changing the value of what ptr to is deemed to change the state of Foo by the creator of Foo, then you'll have to remove const qualifier from the member function.
Marking a function as const means that you can't:
change any of the values of this's ivars
call a non-const function on this or any of its ivars
E.g. it would treat int foo; as const int foo;
These properties aren't transitive to pointers. Factory *_factory; doesn't become const Factory *_factory;, it becomes Factory *const _factory;, which is what you already have.
Imagine if you were using a smart pointer instead, would you expect the compiler to know that it should convert std::shared_ptr<Factory> _factory; into std::shared_ptr<const Factory> _factory;? All it would do is treat it as const std::shared_ptr<Factory> _factory;

C++ Singleton class returning const reference

I have an a class which is singleton as defined follows
class myData {
private:
myData (void); // singleton class.
// Copy and assignment is prohibted.
myData (const myData &);
myData & operator=(const myData &);
static myData* s_pInstance;
public:
~myData (void);
static const myData & Instance();
static void Terminate();
void myFunc() { cout << "my function..." ;}
};
// In cpp file.
myData* myData::s_pInstance(NULL);
myData::myData(){}
myData::~myData()
{
s_pInstance = NULL;
}
const myData& myData::Instance()
{
if (s_pInstance == NULL)
{
s_pInstance = new myData();
}
return *(s_pInstance); // want to avoid pointer as user may deallocate it, so i used const referense
}
void main() {
(myData::Instance()).myFunc();
}
I am getting following error
error C2662: 'myData::myFunc' : cannot convert 'this' pointer from 'const myData' to 'myData&'
how to avoid above problem and call a function from Instance function which is returning const reference?
Thanks!
You'd want to declare func() as a constant member function, so the compiler knows it won't violate the const'd return value from the instance() function.
You could instead also make the instance() function return a 'regular' reference as apposed to a const one.
So either turn:
void myFunc() into void myFunc() const
Or turn:
const myData& myData::Instance() into myData& myData::Instance()
If you are calling a function on a const reference, the function you call must also be const, in your case void myFunc() const.
Otherwise you might return a non-const reference, if that works better.
The error says that myData::Instance() is a const instance of the class, and it can't call myFunc() on that, because myFunc() might change the instance, and you can't change a const instance.
Of course, you know that myFunc() can't really change the instance, but you must advertise this fact, as follows:
void myFunc() const { cout << "my function..." ;}
Avoiding the whole discussion of whether Singleton is a good to have pattern or the source of all evil, if you are actually implementing a singleton, chances are that const correctness will not work there as you expect it, so you should be aware of some pitfalls.
First your error: your Instance() static member returns a const reference, and that means that you can only perform operations that do not modify the object, i.e. call member functions marked as const, or use public members if present in a way that do not modify their values. My suggested solution is modify Instance() to return a non-const reference, rather than making func() const as others suggest.
Now for a longer explanation to the problem of const-correctness in general when applied to your particular Singleton problem. The basic problem is that when you implement a type, you divide those members that modify the object from those that don't, and you mark the latter as const member functions so that the compiler knows of your promise (allows you to call that method on a constant object) and helps you not break it (complains if you try to modify the state in the definition of the method). A method that is marked as const can be applied to both a constant and non constant object, but a method that is not marked const can only be applied to an object that is not const.
Back to the original piece of code, if you implement a singleton and the only way of accessing the object is by an Instance() method that returns a const reference, you are basically limiting all user code to use only const methods implemented in your interface. That means that effectively either all methods are non-mutating, or they are useless (const_cast should never be used). That in turn means that if you have any non-const operation you want to provide an Instance() method that returns a non-const reference.
You could consider implementing two variants of Instance(), but that will not be really helpful. Overload resolution will not help in user code to determine which version to use, so you will end up having to different methods: Instance(), ConstInstance() (choose your names), which means that it is up to user code to determine which one to use. The small advantage is that in their code, the choice of accessor will help documenting their intended usage, and maybe even catch some errors, but more often than not they will just call the non-const version because it works.

const correctness

I was going through: C++ FAQs about inheritance and decided to implement it (just to learn it)
#include "Shape.h"
void Shape::print() const
{
float a = this->area(); // area() is pure virtual
...
}
now, everything (well, almost) works as described in item: faq:23.1 except that print() is const and so it can't access the "this" pointer, as soon as you take out const, it works.
Now, C++ FAQs have been around for a while and are usually pretty good. Is this a mistake?
Do they have typo or am I wrong? If I'm wrong, I would like to know how is it possible to access the "this" pointer in a const function.
The problem is that the area() function is not const. If that function was const, then this would compile fine. Since your inside a const function, the this pointer is const and therefore you can only call const functions on it.
Why couldn't this be accessed? The point is, only const members and methods can be used. So if Shape::area() is declared const, there is no problem. Also, you can freely read data member values, but not assign to them:
class Shape
{
int i;
void print() const;
virtual float area() const = 0;
virtual void modify() = 0;
};
void Shape::print() const
{
float a = this->area(); // call to const member - fine
int j = this->i; // reading const member - fine
this->modify(); // call to non const member - error
this->i++; // assigning to member - error
}
If print is defined as const, then it can use this to access const members but not to access non-const members: so it can invoke this->area() if-and-only-if the area method is declared as const (i.e. if the area method promises that if it's invoked then it won't mutate its Shape instance).
It is also a good practice to declare all functions as const by default, and only not do so when you actually need to modify the object. This will also help finding errors of the kind where some function modifies something it is not meant to.
You certainly can access the this pointer, but in a const function it becomes a pointer to a const object. Remember, the this pointer isn't a real pointer instance, so it can change its type at different points in the program.

Using 'const' in class's functions [duplicate]

This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 5 years ago.
I've seen a lot of uses of the const keyword put after functions in classes, so i wanted to know what was it about. I read up smth at here: http://duramecho.com/ComputerInformation/WhyHowCppConst.html .
It says that const is used because the function "can attempt to alter any member variables in the object" . If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way.
class Class2
{ void Method1() const;
int MemberVariable1;}
So, what is the real definition and use of const ?
A const method can be called on a const object:
class CL2
{
public:
void const_method() const;
void method();
private:
int x;
};
const CL2 co;
CL2 o;
co.const_method(); // legal
co.method(); // illegal, can't call regular method on const object
o.const_method(); // legal, can call const method on a regulard object
o.method(); // legal
Furthermore, it also tells the compiler that the const method should not be changing the state of the object and will catch those problems:
void CL2::const_method() const
{
x = 3; // illegal, can't modify a member in a const object
}
There is an exception to the above rule by using the mutable modifier, but you should first get good at const correctness before you venture into that territory.
Others have answered the technical side of your question about const member functions, but there is a bigger picture here -- and that is the idea of const correctness.
Long story short, const correctness is about clarifying and enforcing the semantics of your code. Take a simple example. Look at this function declaration:
bool DoTheThing(char* message);
Suppose someone else wrote this function and you need to call it. Do you know what DoTheThing() does to your char buffer? Maybe it just logs the message to a file, or maybe it changes the string. You can't tell what the semantics of the call are by just looking at the function declaration. If the function doesn't modify the string, then the declaration is const incorrect.
There's practical value to making your functions const correct, too. Namely, depending on the context of the call, you might not be able to call const-incorrect functions without some trickery. For example, assume that you know that DoTheThing() doesn't modify the contents of the string passed to it, and you have this code:
void MyFunction()
{
std::string msg = "Hello, const correctness";
DoTheThing(msg.c_str());
}
The above code won't compile because msg.c_str() returns a const char*. In order to get this code to compile, you would have to do something like this:
void MyFunction()
{
std::string msg = "Hello, const correctness";
DoTheThing(msg.begin());
}
...or even worse:
void MyFunction()
{
std::string msg = "Hello, const correctness";
DoTheThing(const_cast<char*>(msg.c_str()));
}
neither of which, arguably, are 'better' than the original code. But because DoTheThing() was written in a const-incorrect way, you have to bend your code around it.
The meaning is that you guarantee to clients calling a const function member that the state of the object will not change. So when you say a member function is const it means that you do not change any of the objects member variables during the function call.
const, when attached to a non-static class method, tells the compiler that your function doesn't modify the internal state of the object.
This is useful in two ways:
If you do write code that changes internal state in your const method, the compiler catches the error, moving a programming error from run-time to compile-time.
If client code calls a non-const method on a constant pointer, the compiler catches the error, ensuring the "chain of not changing things" is maintained.
Typically you want to declare all non-mutating non-static class methods as const. This allows calling code to use the const qualifier on pointers, and it helps catch mistakes.
Typical C++: you can declare a class member variable "mutable" and then change it even from a const method.
The const keyword used after a method indicate that this method doesn't modify the object on which it's called. This way, this method can be called on a const version of the object.
If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way?
Well, no. Sometimes you do want instance methods to modify members. For example, any set method will obviously need to set variables, so it's not the case that you should put const everywhere. But if your object's state is totally immutable, first consider whether it might not be better to have no instances at all (i.e., a static class), and if that's not the case, then make everything const.
It's quite unusual not to want to have any member variables changed, but if that's what your class requires, then you should make all your member functions const.
However, you probably do want to change at least some members:
class A {
private:
int val;
public:
A() : val(0) {}
void Inc() { val++; }
int GetVal() const { return val; };
};
Now if I create two instances of A:
A a1;
const A a2;
I can say:
a1.GetVal();
a2.GetVal();
but I can only say:
a1.Inc();
trying to change the value of a constant object:
a2.Inc();
gives a compilation error.