Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new structs on the fly

Tags:

c++

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.

like image 872
woopf Avatar asked Dec 17 '22 15:12

woopf


1 Answers

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) {}
};
like image 151
NPE Avatar answered Dec 19 '22 06:12

NPE