-1

I am trying to add 2 complex numbers by using friend functions and constructors to initialize values but getting error 'Undefined reference to complex1::complex1()' can someone suggest where am I going wrong.

#include<iostream>
using namespace std;

class complex1
{
    float real,img;
public:
    complex1();
    complex1(float a,float b)
    {
        real=a;
        img=b;
    }
    friend complex1 sum(complex1,complex1);
    friend void display(complex1);
};

complex1 sum(complex1 c1,complex1 c2)
{
    complex1 c3;
    c3.real=c1.real+c2.real;
    c3.img=c1.img+c2.img;
    return c3;
}

void display(complex1 c)
{
    cout<<c.real<<"+j"<<c.img;
}

int main()
{
    complex1 c1(100.9,200.9);
    complex1 c2(50.9,50.9);
    complex1 c=sum(c1,c2);
    display(c);     //display and sum is given directly because it is friend
    return 0;
}
  • `complex1 c=sum(c1,c2);` you are constructing `c` with default constructor, which has no implementation (`complex1();` in your class). Then, you are using it in your function `sum`. Also, you are ussing `operator =` with a `complex1` type that was not defined. – Fureeish Oct 06 '17 at 20:53
  • 2
    @Fureeish `operator=` is not a big deal, this will be created by the compiler and since no copy constructor or destructor needs to be defined they are not breaking rule of 3. – Fantastic Mr Fox Oct 06 '17 at 20:56
  • @FantasticMrFox Correct. Gonna leave the comment as it is though for context – Fureeish Oct 06 '17 at 20:57
  • 1
    Where's the content for `complex1()` function (constructor)? – Thomas Matthews Oct 06 '17 at 21:01
  • If your class has covered C++ references (`&`), you should be using them in your parameter lists. – Andrew Lazarus Oct 06 '17 at 21:44

1 Answers1

0

Its nothing to do with the friendliness of your friend function. You declare a constructor:

complex1();

but you never define it. Then you use it in complex1 c3; in sum. You need to define your default constructor:

complex1() {
   //do something
}

Here is a live example.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175