Home > front end >  passing "const ..." as "this" argument discards qualifiers [-fpermissive]
passing "const ..." as "this" argument discards qualifiers [-fpermissive]

Time:02-02

I'm writing a header file to learn more about operator overloading in C , and I got the following error while implementing the division method for two complex numbers.

Here is the source code:

#ifndef __COMP_H
#define __COMP_H

#include <iostream>

class Complex{
private:
    double real;
    double imag;

public:
    //constructor
    Complex(double r=0, double i=0){real = r; imag = i;}

    //operator overloading
    Complex operator   (Complex const &obj){
        Complex res;
        res.real = real   obj.real;
        res.imag = imag   obj.imag;

        return res;
    }

    Complex operator - (Complex const &obj){
        Complex res;
        res.real = real - obj.real;
        res.imag = imag - obj.imag;

        return res;
    }

    Complex operator * (Complex const &obj){
        Complex res;
        res.real = real*obj.real   (-1)*imag*obj.imag;
        res.imag = real*obj.imag   imag*obj.real;
        
        return res;
    }

    Complex operator * (double const i){
        Complex res;
        res.real = i*real;
        res.imag = i*imag;

        return res;
    }

    Complex operator / (Complex const &obj){
        Complex conj(obj.real, (-1)*obj.imag);

        Complex res = (*this)*obj; //numerator
        Complex den = obj*conj; //denominator, it will be 0 as it's imaginary value

        res = res*(1/den.real); //multiply it with a scalar value

        return res;
    }

    void print(){
        std::cout << real << "   " << imag << "j\n";
    }
};



#endif

and the error looks as follows

In file included from main.cpp:2:
comp.h: In member function 'Complex Complex::operator/(const Complex&)':
comp.h:52:27: error: passing 'const Complex' as 'this' argument discards qualifiers [-fpermissive]
         Complex den = obj*conj; //denominator, it will be 0 as it's imaginary value
                           ^~~~
comp.h:32:13: note:   in call to 'Complex Complex::operator*(const Complex&)'
     Complex operator * (Complex const &obj){
             ^~~~~~~~

I've seen other answers on stackoverflow but did not understand it, what is meant by this error and how to fix it? Thanks!

CodePudding user response:

This

Complex operator - (Complex const &obj) { ...

and others are non-const member functions. Member functions are non-const by default, meaning they are declared to modify this. You cannot call them on a const instance. Most of your operators do not modify this, hence should be declared as const:

Complex operator - (Complex const &obj) const { ...
                                      // ^^ 
  •  Tags:  
  • Related