A const member function is not supposed to operate the data member.
However, it can operate the data member if it is a reference data type.
Why can operate the reference data member even if the member function is constant?
It is shown below:
two classes: Bird & BirdHouse
BirdHouse composite two Birds one is object and another one is a reference
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Bird
{
int nb;
public:
Bird(int n):nb(n)
{
}
void set(int i){ nb = i;}
};
class BirdHouse
{
Bird& rb;
Bird b;
int bhn;
public:
BirdHouse( Bird& b1,Bird&b2):rb(b1),b(b2)
{
bhn = b1.get();
}
void set(int a)const //constant member function
{
rb.set(a); //why?reference data member can be assigned a new value
//b.set(a); //it cannot be operated
}
};
int main()
{
}
line 28 the reference can be operated in a constant member function. why?
line 29, the object cannot be operated. This follows the constant member function rules.
thanks in advance