Home > Net >  How is a const class object different from const data member?
How is a const class object different from const data member?

Time:02-21

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?

CodePudding user response:

A const class object doesn't allow the value of any of its data members to be modified outside the constructor. For example:

#include<iostream>
#include<vector>

class emp {
public:
    int emp_count; // Made public for demonstration
    emp() { emp_count = 2; }
    int get_employee_count() const { return emp_count; }
};

int main() 
{
    const emp e1;
    emp e2;
    e1.emp_count = 10; // Compiler error

    std::cout << e1.get_employee_count();
    return 0;
}

But emp_count can still be modified by the constructor:

emp() 
{ 
    emp_count = 2; // This is assignment, not initialization
}

A const data member is a data member that cannot be modified after initialization, neither inside the class nor outside the class.

To initialize a data member, just assign a value to it as such:

class emp 
{
    const int emp_count = 2;
public:

Or initialize it using the constructor as such:

class emp 
{
    const int emp_count;
public:
    emp() : emp_count(2) { } // Initialization of emp_count
    int get_employee_count() const { return emp_count; }
};

Also, consider not using the following line in your code:

using namespace std;

..as it's considered as bad practice.

CodePudding user response:

emp_count=2; is not initialization, it is an assignment. Even if it happens in a constructor. And one cannot assign to const objects.

Use the initializer list to initialize const members:

emp(): emp_count(2) {}

Even better is to use in-class initialization for constants:

class emp{ 
    int emp_count=2;
    public:
    int get_employee_count() const {return emp_count;}
};

This has the advantage of rule-of-zero and it propagates the value to all constructors if any are defined explicitly.

  • Related