Reviewing structures

We have already seen one mechanism in C++ to encapsulate data: struct. A structure allows you to declare data members that are built-in types, pointers, or references. When you create a variable from that struct, you are creating an instance of the structure, also known as an object. You can create variables that are references to this object or pointers that point to the object. You can even pass the object by value to a function where the compiler will make a copy of the object (it will call the copy constructor for the struct).

We have seen that with a struct any code that has access to an instance (even through a pointer or reference) can access the members of the object (although this can be changed). Used like this, a struct can be thought of as aggregate types containing the state.

The members of an instance of a struct can be initialized by accessing them directly with the dot operator or using the -> operator through a pointer to the object. We have also seen that you can initialize an instance of a struct with an initializer list (in braces). This is quite restrictive because the initializer list has to match the data members in the struct. In Chapter 2, Working with Memory, Arrays, and Pointers, you saw that you can have a pointer as a member of a struct, but you have to explicitly take appropriate action to release the memory pointed to by the pointer; if you don't, then this could result in a memory leak.

A struct is one of the class types that you can use in C++; the other two are union and class. Custom types defined as struct or class can have behaviors as well as state, and C++ allows you to define some special functions to control how instances are created and destroyed, copied, and converted. Furthermore, you can define operators on a struct or class type so that you can use the operators on instances in a similar way to using the operators on built-in types. There is a difference between struct and class which we will address later, but in general the rest of the chapter will be about classes and when a class is mentioned you can usually assume the same applies to a struct as well.