Problem debugging operator overloading example

I am recently new with C++ and I am trying to understand operator overloading. I am having the following problem in my .cpp file. Could someone help me out ? I have tried to solve it but I do not know what I am doing wrong. The compiler gives me the error at "complex sum;" in my .cpp. It says "no matching function from call to Complex::Complex". Thanks in advance

Header file (complex.h)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef COMPLEX_H
#define COMPLEX_H


class Complex
{
private:
double re, im;
public:
    Complex(double, double);
    double real();
    double imag();
    double abs();
    Complex operator+(Complex c);

    ~Complex();
};

#endif // COMPLEX_H



.cpp file (complex.cpp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "complex.h"
#include <math.h>
#include <iostream>

using namespace std;

Complex::Complex(double x, double y)
{
    re=x; im=y;
}

double Complex::real()
{
    return re;
}

double Complex::imag()
{
    return im;
}

double Complex::abs()
{
    return(sqrt( (re*re)+(im*im) ));
}

Complex Complex::operator+(Complex c)
{
    Complex sum;
    sum.re = re + c.re;
    sum.im = im + c.im;

    return sum;
}

Complex::~Complex()
{
     cout <<"\nObject Destroyed !\n";
}






Last edited on
Complex::Complex() is the default constructor of the class Complex. It does not exist, because you only get it for free if you provide no other constructors , and you have actually provided one constructor, Complex::Complex(double x, double y) , so Complex::Complex() does not exist.


Complex sum; This is an attempt to use that non-existent constructor, and of course it doesn't work.

That said, it doesn't make any sense where you're trying to use it. The operator += generally takes an already existing object, and alters it. It generally does NOT create a whole new object of the class, which is what you're trying to do there.
Hi Repeater,

You have no idea how much you have helped me. Thank you for understanding that I am a newbie in C++ and that there are simple mistakes and basic questions the we students make as we go along learning how to program. Thanks to you I have managed to solve my issue after having been in another forum and have not obtained any answers for not being "well received by the community" or finding it not to provide any contribution to the community when I have been really struggling for a whole day with this. I really hope the rest of the community is as nice as you. Thank you.

If you would not create a new object for the operator+ overloading , how would you do it ? How can I improve my code ? Your answer would be of great help for me to learn.

1
2
3
4
5
6
7
Complex& Complex::operator+(const Complex& c)
{
    this->re = this->re + c.re;
    this->im = this->im + c.im;

    return *this;
}
Last edited on
Topic archived. No new replies allowed.