Const at the end of function declaration in C++ [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Meaning of “const” last in a C++ method declaration?
In the below function declaration,
const char* c_str ( ) const;
what does the second const do ?

It means the method is a "const method" A call to such a method cannot change any of the instance's data (with the exception of mutable data members) and can only call other const methods.
Const methods can be called on const or non-const instances, but non-const methods can only be called on non-const instances.
struct Foo {
void bar() const {}
void boo() {}
};
Foo f0;
f0.bar(); // OK
fo.boo(); // OK
const Foo f1;
f1.bar(); // OK
f1.boo(); // Error!

That const can only tag onto member functions. It guarantees that it will not change any of the object's data members.
For example, the following would be a compile-time error because of it:
struct MyClass
{
int data;
int getAndIncrement() const;
};
int MyClass::getAndIncrement() const
{
return data++; //data cannot be modified
}

It is a modifier that affects that method (it is only applyable to methods). It means that it will only access, but not modify the state of the object (i.e., no attributes will be changed).
Another subtle change is that this method can only call other const methods (it would not make sense to let it call methods which will probably modify the object). Sometimes, this means that you need two versions of some methods: the const and the non-const one.

Related

Can anybody explain a typical scenario where Const function is necessary? [duplicate]

This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 2 years ago.
#include<iostream>
using namespace std;
class Test {
int value;
public:
Test(int v = 0) {value = v;}
// We get compiler error if we add a line like "value = 100;"
// in this function.
int getValue() const {return value;}
};
int main() {
Test t(20);
cout<<t.getValue();
return 0;
}
Can anybody explain a typical practical scenario where Const function is necessary?
The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided.
A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.
https://www.tutorialspoint.com/const-member-functions-in-cplusplus

Why the use of const in a method with no parameters? [duplicate]

This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
What is meant with "const" at end of function declaration? [duplicate]
(6 answers)
Closed 8 years ago.
why is the purpose of "const" in that case?
std::string List::reqClubName() const
{
return m_Club;
}
Thanks
Banning the modification of members is not the only reason to qualify a member function as const. Whether you want to modify members or not, you can only call a member function on an object through a const context if the member function is marked const:
#include <iostream>
#include <string>
struct List
{
std::string reqClubName()
{
return m_Club;
}
private:
std::string m_Club;
};
int main()
{
const List l;
std::cout << l.reqClubName();
// ^ illegal: `l` is `const` but, `List::reqClubName` is not
}
Neither the language nor the compiler care that reqClubName doesn't try to modify the object anyway; your program will not compile.
Because of this, a const suffix should be your default approach unless you do need to modify a data member.
The const after a member function says that the function does not modify member data in the class it is a part of.

Why does this const member function modifies the static member data? [duplicate]

This question already has answers here:
Why can a const member function modify a static data member?
(4 answers)
Closed 5 years ago.
I have the following line of code from Eckel-Thining in C++
Class Obj{
static int i,j;
public:
void f() const {cout<<i++<<endl;}
void f() const {cout<<i++<<endl;}
};
int Obj::i=47;
int Obj::j=11;
Now it's written in Ecekl for const member functions that by declaring a member function const , we tell the compiler to refrain from modifying a class data. I understand that in some specific cases like mutable const and by explicitly casting away constness of this pointer , we can do away with that but here neither of the two are happening and i++ and j++ working fine. Why is it so?
const is only for object (this pointer is const), modifying static members is allowed.
In a const member function, the object for which the function is called is accessed through a const access path; therefore, a const member function shall not modify the object and its non-static data members.
source:someone cites c++ standard
As you can see, static data member is not protected by const as per c++ standard.

c++ const use in class methods [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
What's the use of const here
Using 'const' in class's functions
Hi All,
I keep making mistakes about the use of const with class methods and variables. For example, sometimes I fix problems using
const int myfunc(const int &obj) const { }
some other times I feel I don't need const at the end since the parameter is already const, so I don't see why I should enforce this fact by appending a const at the end.
const int myfunc(const int &obj) const { }
The first const indicates that the return value is constant. In this particular case, it's not particularly relevant since the int is a value as opposed to a reference.
The second const indicates the parameter obj is constant. This indicates to the caller that the parameter will not be modified by the function.
The third const indicates the function myfunc is constant. This indicates to the caller that the function will not modify non-mutable member variables of the class to which the function belongs.
Regarding #3, consider the following:
class MyClass
{
void Func1() { ... } // non-const member function
void Func2() const { ... } // const member function
};
MyClass c1; // non-const object
const MyClass c2; // const object
c1.Func1(); // fine...non-const function on non-const object
c1.Func2(); // fine... const function on non-const object
c2.Func1(); // oops...non-const function on const object (compiler error)
c2.Func2(); // fine... const function on const object
Noel Llopis wrote a great chapter on const in C++ for Game Developers.
Take a look at his blog post http://gamesfromwithin.com/the-const-nazi for a good explanation of const.
The const at the end indicates the const'ness of a member variable with respect to a class. It indicates it does not change any of the state of a class. The const at the beginning indicates the const'ness of the type int.

What does const mean following a function/method signature? [duplicate]

This question already has answers here:
Meaning of 'const' last in a function declaration of a class?
(12 answers)
Closed 5 years ago.
According to MSDN: "When following a member function's parameter list, the const keyword specifies that the function does not modify the object for which it is invoked."
Could someone clarify this a bit? Does it mean that the function cannot modify any of the object's members?
bool AnalogClockPlugin::isInitialized() const
{
return initialized;
}
It means that the method do not modify member variables (except for the members declared as mutable), so it can be called on constant instances of the class.
class A
{
public:
int foo() { return 42; }
int bar() const { return 42; }
};
void test(const A& a)
{
// Will fail
a.foo();
// Will work
a.bar();
}
Note also, that while the member function cannot modify member variables not marked as mutable, if the member variables are pointers, the member function may not be able to modify the pointer value (i.e. the address to which the pointer points to), but it can modify what the pointer points to (the actual memory region).
So for example:
class C
{
public:
void member() const
{
p = 0; // This is not allowed; you are modifying the member variable
// This is allowed; the member variable is still the same, but what it points to is different (and can be changed)
*p = 0;
}
private:
int *p;
};
The compiler won’t allow a const member function to change *this or to
invoke a non-const member function for this object
As answered by #delroth it means that the member function doesn't modify any memeber variable except those declared as mutable. You can see a good FAQ about const correctness in C++ here