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)'

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

3 Answers 3

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;
};
Sign up to request clarification or add additional context in comments.

Comments

0

You didn't provide a definition for the constructor.

Try:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.