Search code examples
c++constructorcomplex-numbers

complex number addition and using copy constructor


#include<iostream>
using namespace std;
class complex
{
    float real,imag;
public:
    
    complex(complex &c)
    {
        cout<<"copy constructor"<<endl;
        real=c.real;
        imag=c.imag;

    }
    void showData()
    {
        count<<"the sum is"<<endl;
        cout<<real<<"+i"<<imag<<endl;
    }

    complex addition(complex x,complex y)
    {
        complex temp;
        temp.real=x.real+y.real;
        temp.imag=x.imag+x.imag;
        return temp;
    }
};

int main()
{
    complex c2(2,3),c3(c2),c1;
    c2.showData();
    c3.showData();
    c1=c1.addition(c2,c3);
    c1.showData();
    return 0;
}

I would like to add the complex number by passing the value from object and replicating the same value using complex number. This is the error I am getting:

Error:C:\Users\Santosh\Documents\cplusplus\complex_addition.cpp|48|error: no matching function for call to 'complex::complex()'|

Solution

  • You need to define two constructors for the complex class to solve it:

    complex() {}
    complex(float rl, float im) : real(rl), imag(im) {}
    

    The value were never initialized since there were no constructors given to put 2 & 3 in real & imag respectively. The class object c1 will require complex() {} constructor.