What is intention of making a function "const" - c++

Like this,
bool isEmpty() const { return root==NULL; }
This is isEmpty function, test if the BST is empty or not.

It indicates that the function does not modify any of the members of that class.
Usually, the Interface/declaration(through header file) is made available to the users of the class/functions and not the implementation,So the const makes it clear to the user that the function does not modify any members.
Adding the const also makes the user of the function aware that this const member functions should be used when you have an const object.You cannot call normal member function on a const object of that class,it will result in a compiler error.
That is the reason that the function is marked const even if it is empty.It indicates a contract between the function implementer and the user of the function.

When a function is marked as const, the function can be invoked on a const instance of the class. Invoking a non-const function on a const object will lead to a compile-time error.
Basically, you want to mark all functions that don't change the state of your object as const; this way, you can use const as an immutability declaration and the compiler will enforce it for you, by making sure you can only invoke the const functions.
You can invoke const functions on a non-const instance no problem.

It tells the compiler that the function will not modify the state of the class. Also, const functions are the only functions allowed to be called on const objects.

It indicates that the function is logically constant, that is, as far as users of the class are concerned, the value of the class member is not changed by the function. It is legal to call const functions on const references and through const pointers.

Related

I wrote such a member function in Clion, why does the IDE prompt to add const here? [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.

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.

Why static void method() const is compiled error?

I have an interview, the interviewer asked me a question about const and static keyword in C++; The question is why you cannot define a member function like this:
static void func() const
He mentions somewhat *this = null causes this problem, I just did not get his idea, he didn't talk in detail.
The trailing const qualifier is applied to the this pointer that is passed as an implicit argument to each non-static member function. Since the function in question is static, there is no this pointer that could be qualified so the construct is bogus.
The const keyword is used to prevent you from modifying the object that the method is called against. Static methods aren't called against an object, so it doesn't make sense to include them both.
static indicates that the method is a class method and does not operate on a particular instance of that class.
const indicates that the method operates on constant instances of that class.
As static does not operate on instances and const operates on instances, they cannot both apply.

Passing std vector as reference: no matching function to call

I can't see what's wrong with my code. I have a an std::vector which is a private member of my class Foo. It is not declared as const, even when the error the compiler gives suggests so.
(At Foo.h)
private:
std::vector<std::string> tableBackup;
I'm calling a function (from Foo.cpp):
BackupTable(this->tableBackup);
This method is into DatabaseLoad.cpp and .h:
public:
void BackupTable(std::vector<std::string> &tableBackup);
Defined as:
void DatabaseLoad::BackupTable(std::vector<std::string> &tableBackup){
//whatever...
}
I'm getting the following error when I call the method from Foo.cpp:
No matching function for call to 'DatabaseLoad::BackupTable(const std::vector<std::basic_string<char> > &)'
What's the problem? Currently using C++11, but I guess this has nothing to do with that.
You are calling the BackupTable function in a context where the DatabaseLoad object is const-qualified, therefore the compiler is expecting a call to a const-reference.
If you are not planning on modifying the vector, you should declare the function as:
void BackupTable(const std::vector<std::string>& tableBackup);
I can guess that you are calling BackupTable from const method of Foo class
You seem to be calling BackupTable(this->tableBackup); inside a member function which is qualified as const. This means that this is of type const Whatever*, and thus all data members are implicitly const-qualified inside this member function as well. So they cannot be bound to a non-const reference.
You have two sane options:
If BackupTable does not modify its argument, it should accept it as const & instead of just &.
If it does modify its argument, it means the calling function modifies its this object, so it should not be marked as const.
A third (far less likely) option is that tableBackup is actually an implementation details of your class and the fact that it changes does not affect the "logical constness" of the class. If that is so, you can mark it as mutable (that way, even const functions will be able to modify it). At the same time, you must introduce some form of synchronisation mechanism (e.g. a mutex) whenever you access the mutable tableBackup (or any mutable member). The reason is that all of the standard library expects const operations to be thread-safe. An emerging idiom for this is adding a private member like this:
mutable std::mutex mutables;
And locking mutables whenever you access (even just for reading!) a mutable member.
I think that 'this' is const in ' BackupTable(this->tableBackup);'. You call the ' BackupTable' in a 'Foo() const' function.

Don't understand the const method declaration

Too much C# and too little C++ makes my mind dizzy... Could anyone remind me what this c++ declaration means? Specifically, the ending "const". Many thanks.
protected:
virtual ostream & print(ostream & os) const
A const method will simply receive a const this pointer.
In this case the this pointer will be of the const ThisClass* const type instead of the usual ThisClass* const type.
This means that member variables cannot be modified from inside a const method. Not even non-const methods can be called from such a method. However a member variable may be declared as mutable, in which case this restriction will not apply to it.
Therefore when you have a const object, the only methods that the compiler will let you call are those marked safe by the const keyword.
The ending const means that the print function shouldn't be able to change the state of any of the members of the class it is declared in (and therefore cannot call any member functions of that class which are not also declared const).
In the example below, the print function in the class Foo cannot change any of the member variables of Foo (unless they are declared mutable), and cannot call any non-const functions in Foo.
class Foo {
public:
Foo(string value) { m_value = value; }
protected:
ostream & print(ostream & os) const {
m_value = string("foobar"); // won't compile
os << m_value;
return os;
}
private:
string m_value;
};
The const on the method declaration tells the compiler that the function is safe to call on a const object of the type the function is a member of. It also signals to the compiler that the function is not supposed to alter the state of the object and it will not be able to change any member variables that are not marked as mutable.
If you omit the const, this code will not work:
const Foo bar;
bar.print(std::cout); // Will fail to compile unless 'print' is marked const
You're declaring a protected virtual method named print which takes as a parameter a reference to an ostream and returns a reference to an ostream.
The const keyword means the method won't be able to alter the state of the object, the this pointer will be const.
A virtual method is a method whose behavior can be overridden within an inheriting class, basically the virtual keyword gives C++ its' ability to support polymorphism.
And finally if you don't know what is a reference go there
Comming from C# I suppose you know what protected means :)