In the previous article, we saw the different usages of the keyword ‘const’ applied to types. We also observed the interaction of this identifier with pointers and had some examples of which are allowed by the compiler and which are not.
In this second part, we are going to analyze how the keyword ‘const’ is used within the methods of a class. This time we are going to define a class, and then we are going to apply ‘const’ correctness where it is needed.
Here is our relatively simple class. Do not worry, we are going to dissect it step by step:
typedef int myInt;
class AnObject
{
public:
AnObject(){};
void printId () { std::cout<<id_<<std::endl;}
std::string getName () { return name_; }
int getNumber ()
{
if (number_ < 0)
resetNumber();
return number_;
}
void resetNumber () { number_ = 0; }
void helperResetNumber () { resetNumber(); }
void setNumber (int &number) { number_= number; }
void setName (std::string &name ) { name_= name; }
void setId (const myInt id) { id_ = id;}
//The Most Constant Method
const int *const TMCMethod (const int *const& value) const
private:
std::string name_{""};
myInt id_;
int number_;
};
The first two lines that we are going to analyze are the following:
void printId () { std::cout<<id_<<std::endl;}
std::string getName () { return name_; }
As you can see, these member functions are not changing the internal state of the object, therefore they should be constant. This is done by adding the identifier ‘const’ after the parenthesis:
void printId () const { std::cout<<id_<<std::endl;}
std::string getName () const { return name_; }
In general, all functions that only retrieve and/or display information (e.g “getters’) are better defined as constants to make their purpose more clear and readable.
#software-engineering #cpp #coding #programming #‘const’ in c++ (ii)