Why there are two function's versions in one class(const and non-const)? Let's have a test now.
#include <iostream>
using namespace std;
class A
{
public:
A() {}
void fun() { cout<<"I am not const."<<endl; }
void fun() const { cout<<"I am const."<<endl; }
};
int main()
{
A test1;
test1.fun();
const A test2;
test2.fun();
return 0;
}
It is clear to see that the const object will match the const version. However, what happens when we don't have the const member function?
#include <iostream>
using namespace std;
class A
{
public:
A() {}
void fun() { cout<<"I am not const."<<endl; }
// void fun() const { cout<<"I am const."<<endl; }
};
int main()
{
A test1;
test1.fun();
const A test2;
test2.fun();
return 0;
}
An error occurs here. How about lacking of the non-const member function version?
#include <iostream>
using namespace std;
class A
{
public:
A() {}
// void fun() { cout<<"I am not const."<<endl; }
void fun() const { cout<<"I am const."<<endl; }
};
int main()
{
A test1;
test1.fun();
const A test2;
test2.fun();
return 0;
}
It runs well. However, there is a difference--both const!
The conclusion is that const function is more flexible, while the non-const version is relatively strict.
What about the const return values? Let's see.
#include <iostream>
using namespace std;
class A
{
public:
A() { a=0; }
int& fun() { cout<<"I am not const."<<endl; return a; }
const int& fun() const { cout<<"I am const."<<endl; return a; }
void get() { cout<<"Its value is "<<a<<endl; }
private:
int a;
};
int main()
{
A test1;
test1.get();
test1.fun() = 10;
test1.get();
return 0;
}
The value has been changed. Notice that it is a private member value. Now try the const version.
#include <iostream> using namespace std; class A { public: A() { a=0; } int& fun() { cout<<"I am not const."<<endl; return a; } const int& fun() const { cout<<"I am const."<<endl; return a; } void get() { cout<<"Its value is "<<a<<endl; } private: int a; }; int main() { A test1; test1.get(); test1.fun() = 10; test1.get(); const A test2; test2.fun() = 10; return 0; }
In conclusion, through "&" we can change the private value in class, while it doesn't work provided it is a const return value.