Everything in the world has information that goes along with it. Properties. This is where structures are useful. A structure (struct
) allows you to associate variables with each other and create multiple instances of that dataset. An instance of a struct
is an object - a variable of a user-defined datatype.
Declaration
#ifndef EMPLOYEE_HH
#define EMPLOYEE_HH
#include <string>
struct Employee {
std::string name[2];
int id;
int age;
float income;
bool college;
};
#endif
Usage
You can declare an instance of a struct
by using its name. You can also use the dot operator to access elements within the structure.
#include <iostream>
using namespace std;
struct Point {
double x;
double y;
};
int main() {
Point a;
a.x = 3.14;
a.y = 1.27;
cout << a.x << ' ' << a.y;
Point b = a;
}
You can also declare an array of structs...
int main() {
Point dotToDot[27];
dotToDot[18].y = 30.3;
}
Functions
Unlike arrays, structs can be passed into functions be either value or reference. Below are some example functions for working with points.
void add(Point& p, double num) {
p.x += num;
p.y += num;
}
Point add(Point a, Point b) {
a.x += b.x;
a.y += b.y;
return a;
}
Point makePoint(double x, double y) {
Point out;
out.x = x;
out.y = y;
return out;
}
Arrays
A struct
allows for a very simple means of returning and passing an array by value. The compiler knows the exact amount of memory needed to hold a struct.
- Note
- This is actually a very poor method of working with arrays. It will almost never be useful to create a struct that only contains an array.
struct Array10 {
int a[10];
}
void set(Array10& a, int num) {
for (int i = 0; i < 10; i++)
a.a[i] = num;
}
Array10 set(int num) {
for (int i = 0; i < 10; i++)
a.a[i] = num;
}
- Warning
- Out of bounds errors still apply here.
- Note
- If an array is in a struct, it is also copied when the struct is copied.