Search code examples
c++classconstantsoverloadingsubscript

passing ‘const hlp2::Point’ as ‘this’ argument discards qualifiers [-fpermissive]


I have been encountering an issue where I overloaded the [] operator and I am running into issues when compiling my code.

The overload defintion double& Point::operator[](int index) { return index ? y : x; }

The class Point `class Point { public: // declare constructors (3) Point();

Point(double * arr);

//Point(double x_input, double y_input);

Point(const Point& input);

Point(const double x_input, const double y_input);

// declare overloaded operators (8 member functions)
double& operator[](int index);

Point operator+=(double num);

Point operator+=(const Point& pointee);

Point operator++(int);

Point operator++();

Point operator--(int);

Point operator--();

private: double x; // The x-coordinate of a Point double y; // The y-coordinate of a Point };`

The error: error

I am not sure as to why I am encountering this issue and I was hoping if someone can shed some light as to what is happening. Thank you in advance.

I have tried adding const to the overload and its return type but to no avail.


Solution

  • The error message means that the operator [] is called for a constant object of the type Point but the operator is not declared as a constant member function.

    Add one more overload to the operator

    // declare overloaded operators (8 member functions)
    double& operator[](int index);
    const double& operator[](int index) const;
    

    If the operator is defined in the global namespace outside the class definition then you need to write

    const double& hlp2::Point::operator[](int index) const
    {
        //,,,
    }
    

    If the operator is defined in the same namespace where the class is defined then write

    const double& Point::operator[](int index) const
    {
        //,,,
    }
    

    Shortly speaking define it as you defined the non-constant operator.