user2741941
user2741941

Reputation: 343

error: passing ‘const Complex’ as ‘this’ argument of '....' discards qualifiers

I am trying to overload the * operator in C++, in terms of Complex numbers. I also declared a constant I which is inside the class file (Complex.h). The Complex.cpp is the implementation of the class. The main file is for testing. However, it cannot be compiled. How to fix it?

error: passing ‘const Complex’ as ‘this’ argument of ‘Complex Complex::operator*(const Complex&)’ discards qualifiers [-fpermissive]
 cout << "Actual:" << (I * I) << endl;

This is my main file:

#include <iostream>
#include "Complex.cpp"  //remove it 
#include "Complex.h"
using namespace std;
int main (){
    // test multiplication
    cout << "\nExpected:I*I = -1" << endl;
    cout << "Actual:" << (I * I) << endl;
    return 0;
}

This is my Header file:

#ifndef COMPLEX_H
#define COMPLEX_H
#include <cstdlib> //exit
#include <iostream>

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

    double imag() const{
        return b;
    }
    Complex operator*(const Complex& c2);
    private:
    double a;
    double b;
};

//define a constant i
const Complex I(0,1);
#endif

This is the implementation file:

#include "Complex.h"
#include <cmath>

using namespace std;

Complex::Complex(double realNum, double imagNum):a(realNum),b(imagNum){}

Complex::Complex(double realNum):a(realNum),b(0){}

Complex Complex::operator*(const Complex& c2){
    double c = c2.real(), d = c2.imag();
    return Complex((a*c-b*d),(b*c+a*d));
}

Upvotes: 0

Views: 1750

Answers (1)

davidhigh
davidhigh

Reputation: 15488

Your statement (I * I) multiplies two const Complex, and such you can only use the const methods of the class. However, your operator* is available only in a non-const version.

To correct, just declare it as const via

Complex operator*(const Complex& c2) const;

and the same in the implementation.


EDIT: More in detail: You basically have two possibilities to declare a binary operator, either outside a class as

Complex operator*(Complex const& a, Complex const& b);

or inside of it via

Complex operator*(Complex const& a) const;

You chose the in-class version. So, when the compiler sees (I*I), where both are const, it translates the expression into I.operator*(I). In order to do so, however, operator* has to be const as as well, otherwise it can't be called from the constant I. This is because the compiler must assume the method is going to change I, which isn't allowed.

Upvotes: 2

Related Questions