Suppose we have the following code:
#include <iostream>
class Person{
public:
Person(int age);
int get_a();
private:
int a;
};
Person::Person(int age)
{
a = age;
}
int Person::get_a()
{
return a;
}
void Show_Age(Person P)
{
std::cout<<P.get_a()<<std::endl;
}
int main() {
Person P(10);
Show_Age(P);
return 0;
}
Now suppose we have a heavy object, we should pass Person by reference, so we proceed:
void Show_Age(Person &P)
{
std::cout<<P.get_a()<<std::endl;
}
There isn’t a problem, but a good observation is P should be const, we try with it:
void Show_Age(const Person &P)
{
std::cout<<P.get_a()<<std::endl;
}
A compiler failure:
error: passing ‘const Person’ as ‘this’ argument of ‘int Person::get_a()’ discards qualifiers [-fpermissive]
How to solve it?
You should mark
get_aconstin order for this to compile:Doing so tells the compiler that the member function does not modify the state of the object, making it compatible with
constpointers and references.