Category: C++ Structure & Union

https://zain.sweetdishy.com/wp-content/uploads/2026/02/Structure-Union.png

  • Unions in C++

    In C++, a union is a user-defined data type that allows you to store different data types in the same memory location. However, the union can store only one of its member variables at a time, which means that if you assign a value to one member, the previous value stored in another member is overwritten. Where the size of a union is determined by the size of its largest member.

    Union Declaration

    To declare a union, use the union keyword followed by the tag_name (union name) and then declare the union members with their data types inside the curly brackets. Close the declaration with a semicolon.

    Below is the syntax to declare a union −

    union UnionName {
      dataType1 member1;
      dataType2 member2;// more members};

    Example

    Here’s a short example based on the above syntax to declare a union −

    union UnionName {int intValue;// Member for integer valuefloat floatValue;// Member for float valuechar charValue;// Member for character value};

    Declaring Union Variable

    After declaring a union, you need to declare its variable to access and manipulate its members.

    Below is the syntax to declare a union variable −

    union_name variable;

    Accessing Union Members

    You can access union members using the dot operator (.) after declaring a union variable. 

    Below is the syntax to access union members –

    union_variable.member
    

    Example of C++ Union

    Here’s a full example of a union demonstrating it’s working −

    #include <iostream>#include <cstring>usingnamespace std;union Data {int intValue;// Member for integer valuefloat floatValue;// Member for float valuechar strValue[50];// Member for string value};intmain(){// Defining a union variable
      Data data;
    
      data.intValue =2006;
      cout <<"TutorialsPoint: Founded in "<< data.intValue << endl;// overwrites the previous integer value
      data.floatValue =5.75f;
      cout <<"My Float value is: "<< data.floatValue << endl;// overwrites the previous float valuestrcpy(data.strValue,"Hello TutorialsPoint Learner");
      cout << data.strValue << endl;// Accessing the integer after assigning a string
      cout <<"Integer after string assignment: "<< data.intValue << endl;// Undefined behaviorreturn0;}

    When the above code is compiled and executed, it produces the following result −

    TutorialsPoint: Founded in 2006
    My Float value is: 5.75
    Hello TutorialsPoint Learner
    Integer after string assignment: 1819043144
    

    Explanation

    The above-given example demonstrates the use of a union, how it is created and accessed,

    • Firstly, a union named Data is defined with three members: int intValue, float floatValue, char strValue[50], where only one of these members can hold a value at any given time. 
    • As the size of the union is determined by the largest member so in this case (the char array).
    • A union variable data is declared in the int main() body.
    • To assign and access members, all the members are assigned their values by using “.” as data.intValue respectively.
    • For float value, the float member floatValue is assigned the value 5.75.
    • However, since a union can only hold one value at a time the previous value of intValue is overwritten, though it will still occupy the same memory space.
    • Now at last finally when the code attempts to print intValue after it has been overwritten by the string assignment. This leads to undefined behavior, the integer value is no longer valid, and accessing it may give unexpected results as given in the output.

    Anonymous Unions

    Anonymous unions are a special type of union which don’t have a name. This helps in simplifying code by allowing you to direct access to union members without specifying the union variable name.

    Syntax

    Here’s a simple syntax for Anonymous Union, which is declared without any name, allowing direct access to its members −

    union{
      dataType1 member1;
      dataType2 member2;// additional members...};

    Example

    Here’s an example of the above-based syntax for the anonymous union −

    #include <iostream>#include <cstring>usingnamespace std;// Use the standard namespaceintmain(){// Anonymous union declarationunion{int intValue;float floatValue;char strValue[50];};// Assigning an integer value
      intValue =2006;
      cout <<"Integer Value: "<< intValue << endl;// Assigning a float value (overwrites the previous integer value)
      floatValue =3.14 f;
      cout <<"Float Value: "<< floatValue << endl;// Assigning a string value (overwrites the previous float value)strcpy(strValue,"Hello, TutorialsPoint Learner!");
      cout <<"String Value: "<< strValue << endl;// Accessing the integer after string assignment (undefined behavior)
      cout <<"Integer after string assignment: "<< intValue << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Integer Value: 2006
    Float Value: 3.14
    String Value: Hello, TutorialsPoint Learner!
    Integer after string assignment: 1819043144
    

    Union-like Classes

    In C++ a union-like class is defined as a class that includes at least one anonymous union as a member. The data members defined within these anonymous unions are known as variant members. It is the data structures that encapsulate the concept of a union but provide additional features for type safety and usability. 

    These typically use a combination of member variables and a mechanism (like an enumerator) to track which type is currently active.

    Syntax

    Here’s a basic syntax for Union-like classes where the class keyword is used to define the class, followed by the class name class name (here, UnionLikeClass)

    classUnionLikeClass{public:union{
        dataType1 member1;// Member of type dataType1
        dataType2 member2;// Member of type dataType2// additional members...};};

    Example

    Here’s an example of Union-like classes based on the above syntax:

    #include <iostream>#include <cstring>usingnamespace std;classUnionLikeClass{public:// Anonymous union declarationunion{int intValue;// Member for integer valuefloat floatValue;// Member for float valuechar strValue[50];// Member for string value};// Method to display the current valuevoiddisplay(){
        cout <<"Integer Value: "<< intValue << endl;
        cout <<"Float Value: "<< floatValue << endl;
        cout <<"String Value: "<< strValue << endl;}};intmain(){// Creating an instance of UnionLikeClass
      UnionLikeClass data;
    
      data.intValue =2006;
      cout <<"TutorialsPoint: Founded in "<< data.intValue << endl;
    
      data.floatValue =3.14f;
      cout <<"Assigned Float Value: "<< data.floatValue << endl;// Assigning a string value (overwrites the previous float value)strcpy(data.strValue,"Hello, Union Like Class!");
      cout <<"Assigned String Value: "<< data.strValue << endl;// Accessing the integer after string assignment (undefined behavior)
      cout <<"Integer after string assignment: "<< data.intValue << endl;// Undefined behaviorreturn0;}
    TutorialsPoint: Founded in 2006
    Assigned Float Value: 3.14
    Assigned String Value: Hello, Union Like Class!
    Integer after string assignment: 1819043144
  • C++ Structures (struct)

    C++ structures are user-defined data types to group related variables of different types together under a single name. Structures are also known as structs.

    Structures are used to represent a record, suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −

    • Title
    • Author
    • Subject
    • Book ID

    Defining a Structure

    To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member, for your program.

    Syntax

    The format of the struct statement is this −

    struct[structure tag]{
       member definition;
       member definition;...
       member definition;}[one or more structure variables];

    The structure tag is optional and each member definition is a normal variable definition, such as int i; or float f; or any other valid variable definition. At the end of the structure’s definition, before the final semicolon, you can specify one or more structure variables but it is optional.

    Example

    Here is the way you would declare the Book structure −

    structBooks{char  title[50];char  author[50];char  subject[100];int   book_id;} book;

    Accessing Structure Members

    To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type.

    Example

    Following is the example to explain usage of structure −

    #include <iostream>#include <cstring>usingnamespace std;structBooks{char  title[50];char  author[50];char  subject[100];int   book_id;};intmain(){structBooks Book1;// Declare Book1 of type BookstructBooks Book2;// Declare Book2 of type Book// book 1 specificationstrcpy( Book1.title,"Learn C++ Programming");strcpy( Book1.author,"Chand Miyan");strcpy( Book1.subject,"C++ Programming");
       Book1.book_id =6495407;// book 2 specificationstrcpy( Book2.title,"Telecom Billing");strcpy( Book2.author,"Yakit Singha");strcpy( Book2.subject,"Telecom");
       Book2.book_id =6495700;// Print Book1 info
       cout <<"Book 1 title : "<< Book1.title <<endl;
       cout <<"Book 1 author : "<< Book1.author <<endl;
       cout <<"Book 1 subject : "<< Book1.subject <<endl;
       cout <<"Book 1 id : "<< Book1.book_id <<endl;// Print Book2 info
       cout <<"Book 2 title : "<< Book2.title <<endl;
       cout <<"Book 2 author : "<< Book2.author <<endl;
       cout <<"Book 2 subject : "<< Book2.subject <<endl;
       cout <<"Book 2 id : "<< Book2.book_id <<endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Book 1 title : Learn C++ Programming
    Book 1 author : Chand Miyan
    Book 1 subject : C++ Programming
    Book 1 id : 6495407
    Book 2 title : Telecom Billing
    Book 2 author : Yakit Singha
    Book 2 subject : Telecom
    Book 2 id : 6495700
    

    Structures as Function Arguments

    You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example −

    Example

    #include <iostream>#include <cstring>usingnamespace std;voidprintBook(structBooks book );structBooks{char  title[50];char  author[50];char  subject[100];int   book_id;};intmain(){structBooks Book1;// Declare Book1 of type BookstructBooks Book2;// Declare Book2 of type Book// book 1 specificationstrcpy( Book1.title,"Learn C++ Programming");strcpy( Book1.author,"Chand Miyan");strcpy( Book1.subject,"C++ Programming");
       Book1.book_id =6495407;// book 2 specificationstrcpy( Book2.title,"Telecom Billing");strcpy( Book2.author,"Yakit Singha");strcpy( Book2.subject,"Telecom");
       Book2.book_id =6495700;// Print Book1 infoprintBook( Book1 );// Print Book2 infoprintBook( Book2 );return0;}voidprintBook(structBooks book ){
       cout <<"Book title : "<< book.title <<endl;
       cout <<"Book author : "<< book.author <<endl;
       cout <<"Book subject : "<< book.subject <<endl;
       cout <<"Book id : "<< book.book_id <<endl;}

    When the above code is compiled and executed, it produces the following result −

    Book title : Learn C++ Programming
    Book author : Chand Miyan
    Book subject : C++ Programming
    Book id : 6495407
    Book title : Telecom Billing
    Book author : Yakit Singha
    Book subject : Telecom
    Book id : 6495700
    

    Pointers to Structures

    You can define pointers to structures in very similar way as you define pointer to any other variable as follows −

    Syntax

    structBooks*struct_pointer;

    Now, you can store the address of a structure variable in the above defined pointer variable. To find the address of a structure variable, place the & operator before the structure’s name as follows −

    Syntax

    struct_pointer =&Book1;

    To access the members of a structure using a pointer to that structure, you must use the -> operator as follows −

    Syntax

    struct_pointer->title;

    Example

    Let us re-write above example using structure pointer, hope this will be easy for you to understand the concept −

    #include <iostream>#include <cstring>usingnamespace std;voidprintBook(structBooks*book );structBooks{char  title[50];char  author[50];char  subject[100];int   book_id;};intmain(){structBooks Book1;// Declare Book1 of type BookstructBooks Book2;// Declare Book2 of type Book// Book 1 specificationstrcpy( Book1.title,"Learn C++ Programming");strcpy( Book1.author,"Chand Miyan");strcpy( Book1.subject,"C++ Programming");
       Book1.book_id =6495407;// Book 2 specificationstrcpy( Book2.title,"Telecom Billing");strcpy( Book2.author,"Yakit Singha");strcpy( Book2.subject,"Telecom");
       Book2.book_id =6495700;// Print Book1 info, passing address of structureprintBook(&Book1 );// Print Book1 info, passing address of structureprintBook(&Book2 );return0;}// This function accept pointer to structure as parameter.voidprintBook(structBooks*book ){
       cout <<"Book title : "<< book->title <<endl;
       cout <<"Book author : "<< book->author <<endl;
       cout <<"Book subject : "<< book->subject <<endl;
       cout <<"Book id : "<< book->book_id <<endl;}

    When the above code is compiled and executed, it produces the following result −

    Book title : Learn C++ Programming
    Book author : Chand Miyan
    Book subject : C++ Programming
    Book id : 6495407
    Book title : Telecom Billing
    Book author : Yakit Singha
    Book subject : Telecom
    Book id : 6495700
    

    The typedef Keyword

    There is an easier way to define structs or you could “alias” types you create.

    Example

    typedefstruct{char  title[50];char  author[50];char  subject[100];int   book_id;} Books;

    Now, you can use Books directly to define variables of Books type without using struct keyword. Following is the example −

    Books Book1, Book2;

    You can use typedef keyword for non-structs as well as follows −

    typedeflongint*pint32;
     
    pint32 x, y, z;

    x, y and z are all pointers to long ints.