I have 2 sample codes below:
#include<iostream>
#include<vector>
using namespace std;
class emp{
int emp_count;
public:
emp(){emp_count=2;}
int get_employee_count() const {return emp_count;}
};
int main(){
const emp e1;
cout<<e1.get_employee_count();
return 0;
}
Above code works fine, however, below code gives an error for trying to change a read-only value:
#include<iostream>
#include<vector>
using namespace std;
class emp{
const int emp_count;
public:
emp(){emp_count=2;}
int get_employee_count() const {return emp_count;}
};
int main(){
emp e1;
cout<<e1.get_employee_count();
return 0;
}
A const class object doesn't let me change the value of the data member, but based on the above example, how is a const class object different from a const data member as I am able to assign the value in the constructor body in the 1st code, while the 2nd code restricts me to do the same?