Skip to main content

Chapter 15 Structs

Imagine you are writing a program that makes use of lots of points on the x, y plane. Each point requires two doubles - an x coordinate and a y coordinate - to represent. We can create two variables like x1 and y1 and think of the pair as our โ€œpointโ€, but there are many issues this will lead to:
  • We have to remember that the variables โ€œgoโ€ with each other. Other than the names looking similar, there is nothing that links the two together.
  • We have to pass two variables to functions to pass the โ€œpointโ€.
  • We canโ€™t return two variables from a function. So there is no way to return a โ€œpointโ€.
  • We canโ€™t store a list of points in a vector. Instead, would need one vector with x values and another with y values.
What we really need is a new data type that combines the two variables together.
In this chapter, we will learn to build our own new data types by aggregating (combing) multiple simpler pieces of data.