Composite Data Type

Structures (Struct)

Same syntax for both C and C++.

struct tod {
	int hours; 
	int minutes;
};
 
struct tod now = {16,50};

If you initialize with a value, all other properties will be initialized to 0.

Make sure not to confuse it with a Class, which is Object-Oriented Programming.

Use typedef in front of struct to make your life easier.

typedef struct tod {
	int hours; 
	int minutes;
} tod;
 
tod now = {16,50};

Struct in C++

In C++, you don’t need the typedef word, and directly use the struct

struct tod {
	int hours; 
	int minutes;
};
 
tod now{16,50};
  • Also, you can just use the {} initializers
Class vs. Struct
  • Use struct when all you want is structured data, and
  • Use classes when you want methods, Inheritance, or generics

See Class