Peter Gordon
Peter Gordon

Reputation: 11

C++ passing an array of classes

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

Upvotes: 1

Views: 163

Answers (3)

user425495
user425495

Reputation:

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;
};

Upvotes: 2

olegarch
olegarch

Reputation: 3891

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

Upvotes: 0

user1508519
user1508519

Reputation:

You didn't provide a definition for the constructor.

Try:

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

Upvotes: 0

Related Questions