Structures in C++

Dated Jun 4, 2022; last modified on Sat, 04 Jun 2022

A struct helps us organize the elements that a type needs into a data structure, e.g.

struct Vector {
  int sz;         // number of elements
  double* elem;   // pointer to elements on the free store
};

void vector_init(Vector& v, int s) {
  v.elem = new double[s];
  v.sz = s;
}

However, notice that a user of Vector has to know every detail of a Vector’s representation. We can improve on this.

There is no fundamental difference between a struct and a class; a struct is simply a class with members public by default.

  1. A Tour of C++ (Second Edition). Chapter 2. User-Defined Types. Bjarne Stroustrup. 2018. ISBN: 978-0-13-499783-4 .