I have two classes Triangle and ALine and I want to assign new ALine instances to properties of Triangle in its constructor.
But I am getting this error
Undefined symbols for architecture x86_64:
"ALine::ALine()", referenced from:
Triangle::Triangle(triangle) in Triangle.o
ld: symbol(s) not found for architecture x86_64
Below is code I wrote:
ALine.cpp
#include "Geometry.h"
#include "ALine.h"
ALine::ALine(point a, point b)
{
double tmpy = a.y - b.y;
double tmpx = a.x - b.x;
double tmpk;
if(equals(tmpy, 0))
{
tmpk = 0;
}
else
{
tmpk = tmpx/tmpy;
}
double tmpq = a.y - tmpk*a.x;
if(equals(tmpx, 0))
{
if(equals(a.x, 0))
{
if(equals(b.x, 0)) tmpk = 0;
else tmpk = (b.y-tmpq)/b.x;
}
else
{
tmpk = (a.y-tmpq)/a.x;
}
}
a = a;
b = b;
k = tmpk;
q = tmpq;
};
ALine.h
class ALine{
private:
double k;
double q;
point a;
point b;
double length;
void calculateLength();
public:
ALine(point a, point b);
ALine();
point getK();
point getQ();
static bool areinline(point a, point b, point c);
};
Triangle.cpp
#include "Triangle.h"
#include "Geometry.h"
#include "ALine.h"
Triangle::Triangle(triangle t)
{
triangle itself = t;
a = *new ALine(itself.a, itself.b);
b = *new ALine(itself.b, itself.a);
c = *new ALine(itself.c, itself.a);
};
Note, the classes are not complete, I pasted here only relevant code to my problem (if not, I can add more).
You’re declaring a default constructor but not defining one.
You’re telling the compiler that the function exists, so it’s letting you use it. This is legal. However, when the linker tries to process the compiled code, it looks for
ALine::ALine()and can’t find it, because you never said what it was.Add to your ALine.cpp something like the following:
That being said
You are not using dynamic allocation correctly. As it currently is, you allocate a new ALine on the heap, copy it into an ALine on the stack, and then discard the address of the heap ALine (not once but 3 times). This is a memory leak, the ALines never go away and as long as your program is running, they will always be there.
You would be much better off changing
Triangle::Triangle(triangle other)to the following:This uses the syntax of
Class::Class(args ...) : member(...), member2(...), ... { /* body */ }to initialize the members of a class in a constructor. One benefit of this is that their default constructors will not be called, as they would (implicitly) in your code.