C++ Structures (struct)
Lesson outline
Introduction to Structures
In C++, a structure (struct) is a user-defined type that lets you group different kinds of variables under a single name.
Structures are useful for representing records with multiple attributes and are fundamental when modeling more complex data.
Basic Structure Syntax
Creating Structure Variables
You can declare structure variables in different ways:
Accessing Structure Members
Use the dot operator (.) to access members of a struct:
Initializing Structures
Structures can be initialized in several ways:
Structures vs Classes
| Feature | struct | class |
|---|---|---|
| Default member access | public | private |
| Default base-class inheritance access | public | private |
| Usage (convention) | Often for plain data carriers | Often for encapsulation (data + behavior) |
| Methods/ctors/dtors | Fully supported | Fully supported |
| Memory model | Same as class | Same as struct |
Nested Structures
A structure can contain another structure as a member:
Arrays of Structures
You can create arrays of structures to manage groups of records:
Pointers to Structures
Access struct members via pointers using the arrow operator (->):
Structures with Functions
Structs can be passed to and returned from functions:
Structure Methods
Structs can also define member functions:
Constructors in Structures
Structures can have constructors just like classes:
Real-World Example: Student Records
Here's a complete example showing a struct with methods and an array of student records:
Best Practices
- Prefer structs for simple data aggregates; use classes when you need encapsulation or invariants.
- Initialize all members (default member initializers or constructors help).
- Use member functions for operations specific to the struct's data.
- Consider operator overloading when it makes usage clearer.
- Prefer smart pointers over raw ownership for dynamically allocated structs.
- When passing structs to functions: pass small/trivial types by value; for larger ones, prefer const reference unless you need to modify.