0

I'm trying to create a class of complex numbers in C++, but I'm getting a strange error for the initialiser of the class here is a screenshot of the error :

enter image description here

And here is my code :

main.cpp :

#include <iostream>
#include "cmath"
#include "Complexx.h"


int main(int argc, const char * argv[])
{

complex c(1,1);
std::cout << c.realPart << "+" <<c.imaginaryPart << "i";
return 0;
}

Complexx.h :

#ifndef Functions_Complexx_h
#define Functions_Complexx_h
#include "cmath"
using namespace std;

class complex {

public:
double imaginaryPart;
double realPart;
complex(double realPart, double imaginaryPart);
double modulus();
};
#endif

What am I doing wrong here?

Moray
  • 321
  • 2
  • 9

3 Answers3

3

The problem is here.

complex(double realPart, double imaginaryPart);

You've declared a constructor, but you haven't defined it. That's why the linker is complaining about undefined symbol complex::complex(double, double)

This is probably the definition you want - to store those two parameters in the object.

complex(double realPart, double imaginaryPart)
  : realPart(realPart)
  , imaginaryPart(imaginaryPart)
{ }

It doesn't matter what those parameters are named. C++ will not infer that because they have the same names as your member variables that they should be copied to the object.

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
2

You haven't provided a definition for the complex(double, double) constructor, although a declaration is provided. This is what the linker complains about.

Add this to a .cpp file in your project which #includes your header file complexx.h (possibly complexx.cpp):

complex::complex(double realPart, double imaginaryPart)
    :
    realPart(realPart),
    imaginaryPart(imaginaryPart)
{ }

It is possible that the same problem exists for double modulus(), for which no linker error is issued because you are not invoking it (yet).

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
0

It seems that you haven't linked the definition of the complex(double, double) constructor. This may be caused by the fact that you forgot to link Complexx.cpp (assuming the name of the cpp file is the same as the header file) or that you totally forgot to define the constructor inside the linked Complexx.cpp file.

Just run this g++ commands when compiling main.cpp (assuming you are using gcc):

g++ -c Complexx.cpp -o Complexx.o
g++ -c main.cpp -o main.o
g++ main.o Complexx.o -o app
Shoe
  • 74,840
  • 36
  • 166
  • 272