Part two: constant methods.

In C++, the qualifier ‘const’ specifies a compile-time constraint that an object or variable cannot be modified. The compiler verifies that the object or variable never changes and stops you when you try to modify it or re-assign it. However, writing ‘const’ correct code is way more challenging than just using the keyword in some lines, and then allowing the compiler to figure out what makes sense. In this three-part guide, you will get some hints on how to use it properly.

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)

Understanding correctly that messy keyword ‘const’​ in C++ (II)
1.20 GEEK