🏗️Structure
Collection of different data types
Basic Definition: A struct is defined using the
struct
keyword, followed by the struct name and a block containing member variables.Creating Instances: You can create instances of a struct like this:
Member Access: Access struct members using the dot (.) operator:
Functions in Structs: Structs can also contain functions (methods):
Constructors: You can define constructors for initialization:
Default Access Specifier: In a struct, members are public by default (unlike in classes where they're private by default).
Nested Structs: You can nest structs within other structs:
Pointers to Structs: You can create pointers to structs and access members using the arrow (->) operator:
Struct vs Class: The main difference is the default access specifier. Structs are often used for simple data structures, while classes are used for more complex objects with behaviors.
Memory Alignment: Structs can have padding between members for memory alignment. You can use
#pragma pack
or__attribute__((packed))
to control this.
Example:
Run it here.
Last updated