The Wayback Machine - https://web.archive.org/web/20250402105715/https://www.geeksforgeeks.org/structures-in-cpp/
Open In App

Structures in C++

Last Updated : 19 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

C++ Structures are user defined data types which are used to store group of items of different data types. A structure creates a data type that can be used to group items of possibly different types into a single type.

Syntax

Before using structure, we have to first define the structure. The struct keyword is used to define a structure as shown:

C++
struct name{
    type1 mem1;
    type2 mem2;
    ...
};

where structure name is name and mem1, mem2 and mem3 are the items it groups. They are also called its members or fields.

Example:

The above is also called Structure Definition. It is not allocated any memory and cannot be used in the program directly. We have to create its variables to use it.

Create Structure Variable

Once the structure is defined, its variable can be created in a similar way as basic data type variables.

C++
struct_name var_name;

where struct_name is the name of the structure and var_name is the name of the variable.

A variable can also be declared with the definition of the structure:

C++
struct name{
    type1 mem1;
    type2 mem2;
    ...
}var1, var2;

Initialize Structure Members

Structure members cannot be initialized with declaration. For example, the following C++ program fails in compilation.

C++
struct Point {
   int x = 0;
   int y = 0;
}; 

Structure members can be initialized to values provided in the curly braces ‘{}’. For example,

C++
struct Point {
    int x, y;
};

int main() {
    
    // Initialize data members of
    // structure using curly braces
    struct Point p1 = { 0, 1 };

    
//Driver Code Starts{
    return 0;
}
//Driver Code Ends }

The values provided in the curly braces {} are sequentially assigned to the members of the structure. In the above example, 0 is assigned to member x, and 1 is assigned to member y.

Since C++ 20, we can also use Designated Initializers to initialize the structure members.

Access and Modify Members

Structure members are accessed using dot operator (.) as shown:

C++
var_name.member_name;

where var_name is structure variable and member_name is the name of the structure member. A new value to this member can also be assigned using assignment operator.

C++
var_name.member_name = new_val;

The new value should be of the same type to avoid type mismatch error.

Example:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;
//Driver Code Ends }

struct Point {
    int x, y;
};

int main() {
    struct Point p = { 0, 1 };
    
    // Accessing members
    cout << p.x << " ";
    cout << p.y << endl;
    
    // Updating members
    p.x = 99;

    // Accessing members again
    cout << p.x << " ";
    cout << p.y;

//Driver Code Starts{
    
    return 0;
}
//Driver Code Ends }

Output
0 1
99 1

Member Functions

In C structures, functions were not allowed inside the structure but in C++, we can declare the function inside the structure. They are called member functions while the variables are called data members. C++ structure is way more similar to C++ classes as compared to C structures.

Example:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

struct Point {
    int x, y;
    
    // Member function
    int sum(){
        return x + y;
    }
};

int main() {
    Point s = { 0, 1 };

    // Call member function 
    // using (.) operator
    cout << s.sum();

//Driver Code Starts{

    return 0;
}
//Driver Code Ends }

Output
1

C++ structures also support other class components such as constructor, destructor, access specifiers, etc.

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

// Class like structure
struct Point {
private:
    int x, y;
public:

    // Constructors
    Point(int a, int b) {
        x = a;
        y = b;
    }
    
    // Member function
    void show() {
        cout << x << " " << y << endl;
    }
    
    // Destructor
    ~Point() {
        cout << "Destroyed Point Variable" << endl;
    }
};

int main() {
    
    // Creating Point variables using constructors
    Point s1;
    Point s2(99, 1001);

    s1.show();
    s2.show();

//Driver Code Starts{
    return 0;
}
//Driver Code Ends }

Output
1 1
99 1001
Destroyed Point var
Destroyed Point var

Size of Structure

The size of a structure is determined by the sum of the sizes of its individual data members, with additional padding added by the compiler to ensure proper memory alignment.

Example:

C++
#include <iostream>
using namespace std;
struct GfG {
    char c;
    int x, y;
};

int main() {
    
    // Finding the size
    cout << sizeof(GfG);
    
    return 0;
}

Output
12

Ideally, the size should be the size of all data members i.e. sizeof(char) + 2 * sizeof(int) = 1 + 8 = 9 bytes. But the size comes out to be 12 bytes. This is due to the mentioned structure padding.

Member functions does not contribute to the size of the structure. Also, in C++, size of the structure cannot be 0. Refer to this article to know more – Why empty Structure has size 1 byte in C++ but 0 byte in C?

typedef

In C++, typedef is used to create an alias for an existing variable. Similarly, with structures, typedef creates an alias for the original name of the structure.

Example:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

typedef struct GeeksforGeeks {
    int x, y;
    
// Alias is specified here
} GfG;

int main() {
    
    // Using alias
    GfG s = { 0, 1 };
    cout << s.x << " " << s.y << endl;

//Driver Code Starts{
    return 0;
}
//Driver Code Ends }

Output
0 1

Nested Structure

Nested structure in C++ refers to a structure that is defined inside another structure. Just as structure members are declared within a structure, one structure can be declared as a member inside another structure.

Example:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

// Define inner structure
struct inner {
    int a, b;
};

// Define the outer structure that 
// contains inner structure
struct outer {
    
    // Nested structure
    inner in; 
    int x, y;
};

int main() {
    outer obj = {{1, 2}, 10, 20};

//Driver Code Starts{
    cout << "Inner: " << obj.in.a << " "
    << obj.in.b << endl;
    cout << "Outer: " << obj.x << " "
    << obj.y;

    return 0;
}
//Driver Code Ends }

Output
Inner: 1 2
Outer: 10 20

Notice how there are one more curly braces added in the initialization. This is to initialize the inner structure.

The inner structure can also be defined directly inside the outer structure even without naming the structure and just by creating a variable name.

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

// Define the outer structure that 
// contains inner structure
struct outer {
    
    // Nested structure
    struct inner{
        int a, b;
    }in;
    int x, y;
};

//Driver Code Starts{

int main() {
    outer obj = {{1, 2}, 10, 20};
    cout << "Inner: " << obj.in.a << " "
    << obj.in.b << endl;
    cout << "Outer: " << obj.x << " "
    << obj.y;

    return 0;
}
//Driver Code Ends }

Output
Inner: 1 2
Outer: 10 20

Pointer to Structure

In C++, a pointer to a structure is also known as a structure pointer. It is a pointer that holds the address of the memory location where the structure is stored. The normal way to access structure members is to first dereference the pointer and then use dot operator, but C++ provides –> arrow operator to directly access structure members using pointer to it.

Example:

C++
//Driver Code Starts{
#include <iostream>
using namespace std;

//Driver Code Ends }

struct GfG {
    int count;
    void showCount() {
        cout << count << endl;
    }
};

int main() {
    GfG gfg = {224};
    
    // Creating pointer
    GfG *sptr = &gfg;
    
    // Accessing using arrow operator
    sptr->showCount();

//Driver Code Starts{
    return 0;
}
//Driver Code Ends }

Output
224

Self-Referential Structures

Self-referential structures are those structures that contains the pointer to the same type as a member. For example,

C++
// Self referential structures
struct GfG {
    int val;
    
    // Pointer to same type
    GfG *next;
}

Such kind of structures are used in data structures such as linked list, trees, etc.

A structure can only contain pointer to the same type but not variable of same type. It is because it is impossible to derive the size information in the structure before complete definition.

Structure with Function

Structures work similarly like other variables with functions. We can pass a structure to a function or return a structure from a function, just like with other variables. Additionally, we can pass a structure either by value or by reference. However, the recommended approach is to pass a structure by reference, as making a copy of a structure is a costly operation.

Structures are also used return multiple values from the function. Refer to the article to know more – Structure with Functions

Bit Fields

Bit fields in structures allows us to define the number of bits that a particular data member will occupy. Basically, it specifies the manual size of the structure member in bits. It is useful in memory critical applications such as embedded systems.

Structure vs Class

In C++, a structure works similarly to a class, but there are some key differences in between of them. The important difference is how implementation details are handled.

By default, a structure does not provide its implementation details, allowing them to be accessed by anyone using the structure. In other hand, a class hides its implementation details by default, thus preventing the programmer from accessing them.

C++ Structure – FAQs

How is a structure different from a class in C++?

The main difference is that, by default, members of a structure are public, whereas members of a class are private by default.

Can a structure have functions in C++?

Yes, a structure can have member functions just like a class. However, this is less common in basic usage.

Can we assign one structure variable to another in C++?

Yes, you can assign one structure variable to another, and all members will be copied.

What is a structure tag in C++?

The structure tag is the name given to the structure definition. For example, in struct Employee { … };, Employee is the structure tag.

How do you access members of a structure in C++?

You can access members of a structure using the dot operator (.) for structure objects and the arrow operator (->) for structure pointers.



Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg