1

Can anybody help me with the syntax of passing an array of classes to another class. The syntax of passing an array of classes to another class has got me beaten. class line tries to be initialised by an array of points, but the prototype does not match.

#include    <iostream>
using namespace std;
class point {
public:
    point() {}
    point(int x, int y) : X(x), Y(y) {}
    void setXY(int x, int y) { X = x; Y = y; }
    int getX() { return X; }
    int getY() { return Y; }
private:
    int X, Y;
};
class line {
public:
    line(point *points, int);  // Problem line.
private:
    point *coords;
    int numpoints;
};
int main() {
    point   points[3];
    points[0].setXY(3, 5);
    points[1].setXY(7, 9);
    points[2].setXY(1, 6);

    line    l(points, 3);    // Problem line.
    return 0;
}

Error message: cygdrive/c/Tmp/cc4mAXRG.o:a.cpp:(.text+0xa7): undefined reference to `line::line(point*, int)'

  • 2
    "undefined reference" is a linker error, indicating that the definition (body) of the constructor `line(point *, int)` could not be found. – dyp Sep 18 '13 at 02:05
  • Wow two answers and a comment in the exact same second. – dyp Sep 18 '13 at 02:06
  • Use `std::array` or `std::vector`, depending on your needs. – chris Sep 18 '13 at 02:15

3 Answers3

2

You need to define a constructor for your line class - you've only provided a declaration.

#include    <iostream>
using namespace std;
class point {
public:
    point() {}
    point(int x, int y) : X(x), Y(y) {}
    void setXY(int x, int y) { X = x; Y = y; }
    int getX() { return X; }
    int getY() { return Y; }
private:
    int X, Y;
};
class line {
public:
    line(point *points, int count)
     : coords(points), numpoints(count) {}
private:
    point *coords;
    int numpoints;
};
int main() {
    point   points[3];
    points[0].setXY(3, 5);
    points[1].setXY(7, 9);
    points[2].setXY(1, 6);

    line    l(points, 3);
    return 0;
}

I'd recommend taking a look at the difference between definitions and declarations. Additionally, you should consider maintaining a std::vector<point> in your line class to manage the points. Your line class might then behave as:

#include <vector>
class line {
public:
    line(std::vector<point> points)
     : coords(points), numpoints(coords.size()) {}
private:
    std::vector<point> coords;
    int numpoints;
};
Community
  • 1
  • 1
0

You didn't provide a definition for the constructor.

Try:

line(point *points, int np) : coords(points), numpoints(np) {}
0

Missing body of constructor "line". You define prototype only.

olegarch
  • 3,347
  • 1
  • 16
  • 14