woopf
woopf

Reputation: 83

Creating new structs on the fly

I am (very) new to C++, and am having some issues understanding structs. I'm using example code from a course, so I have:

struct Point {
   int x;
   int y;
}

In another bit of code, I want to write the following:

drawLine(point1, new Point(x, y));

This does not work, and I understand that I am trying to declare a struct as if it were a class, but is there a way to do this? I have currently written a helper function which returns a Point from an x,y, but this seems roundabout.

Upvotes: 4

Views: 9958

Answers (3)

NPE
NPE

Reputation: 500883

The problem isn't that you're trying to declare a struct as if it were a class (in fact, there's very little difference between the two in C++).

The problem is that you're trying to construct a Point from two ints, and there ins't a suitable constructor. Here is how you can add one:

struct Point {
   int x;
   int y;
   Point(int x, int y): x(x), y(y) {}
};

Upvotes: 9

tomsv
tomsv

Reputation: 7277

The difference between struct and class in c++ is not that huge. Why don't you add a constructor to your struct?

Upvotes: 0

Fred Foo
Fred Foo

Reputation: 363817

new returns a pointer. Just drawLine(point1, Point(x,y)) should work if you define the appropriate constructor for Point.

(drawLine(point1, *(new Point(x,y))) would also work, but would introduce a memory leak; every new should be balanced by a delete.)

Upvotes: 3

Related Questions