Fan
Fan

Reputation: 217

Overloading == operator causes discards qualifiers error

I am making a complex number class using C++. And I want to overload the == operator. But I got this error:

In file included from Complex.cpp:1:0,
             from testComplex.cpp:2:
Complex.h: In function ‘bool operator==(const Complex&, const Complex&)’:
Complex.h:29:21: error: passing ‘const Complex’ as ‘this’ argument of ‘double Complex::real()’ discards qualifiers [-fpermissive]
     return (c1.real() == c2.real() && c1.imag() == c2.imag());

Here is my class file:

#ifndef COMPLEX_H
#define COMPLEX_H

class Complex{
    public:
    Complex(void);
    Complex(double a, double b);
    Complex(double a);
    double real(){ 
        return a;
    }

    double imag(){
        return b;
    }
    private:
    double a;
    double b;
};

bool operator==(const Complex& c1, const Complex& c2){
    return (c1.real() == c2.real() && c1.imag() == c2.imag());
}
#endif

How to fix it?

Upvotes: 2

Views: 1982

Answers (1)

Nard
Nard

Reputation: 1006

The compiler is basically saying that you seem to be using a function of a read-only object that is allowed to alter it. Imagine if you could call a member function say IncrementImaginary(); on a read-only Complex object, you'd be altering a read-only object!

This is why when your member functions do not alter the variables (i.e. the state) of your class, you should attach a const qualifier to them like this:

double real() const{
  return a;
}

This way, the compiler will know that it is safe to run this function on a read-only object of your class.

Upvotes: 1

Related Questions