Structs and Unions

Let's learn about structs and unions in this lesson.

Structs #

Introduction #

A Structure in C++ is a group of data elements grouped together under one name. These data elements, known as members, can be of different types and sizes. It is a user-defined data type that allows us to combine data items of different kinds.

The scope of Struct #

Structs are almost identical to classes. The default access specifier for a struct is public instead of private.

The default inheritance specifier is public instead of private.

Example #

Let’s consider an example of a Person struct which contains age, size, weight, and name as members. A struct always ends with a ;.

struct Person{
int age;
int size;
int weight; 
std::string name;
};

Structs should be used instead of classes if the data type is a simple data holder.

Get hands-on with 1400+ tech skills courses.