fbpx

A Beginner's Guide to Structs in C++ Programming

Introduction to Structures in C++

INTRODUCTION

Structures, or structs, in C++ are user-defined data types that allow you to group variables of different types under a single name. They provide a way to model complex data by combining related variables, making code more organized and easier to manage.

  1. Custom Data Types: You can define a structure to represent an entity like a person, point, or product with multiple attributes.
  2. Flexibility: Structures allow variables of various types to coexist in a single unit.
  3. Initialization Options: Members of structures can be initialized during declaration or later in the code.

Imagine modeling a person with attributes like name, age, and height. Instead of creating separate variables

In C++, structures (or structs) are user-defined data types that allow you to group variables of different types under a single name

This can be quite useful when you want to model complex data. Here’s a simple example to illustrate how you can define and use a structure in C++:

Syntax:

struct

{

   // Declaration of the struct

}

#include <iostream>

using namespace std;

 

// Define a structure named ‘Person’

struct Person {

    string name;

    int age;

    float height;

};

 

int main() {

    Person person1;

    person1.name = “Alice”;

    person1.age = 30;

    person1.height = 5.6;

 

    // Output the values

    cout << “Name: ” << person1.name << endl;

    cout << “Age: ” << person1.age << endl;

    cout << “Height: ” << person1.height << ” feet” << endl;

 

    return 0;

}

how to declare structure variables?

// A variable declaration with structure declaration.

struct Point

{

   int x, y;

} p1;  // The variable p1 is declared with ‘Point’


// A variable declaration like basic data types

struct Point

{

   int x, y;

};

 

int main()

{

   struct Point p1;  // The variable p1 is declared like a normal variable

}

struct Point

{

   int x = 0;  // COMPILER ERROR:  cannot initialize members here

   int y = 0;  // COMPILER ERROR:  cannot initialize members here

};

 

// In C++ We can Initialize the Variables with Declaration in Structure.

 

#include <iostream>

using namespace std;

 

struct Point {

    int x = 0; // It is Considered as Default Arguments and no Error is Raised

    int y = 1;

};

 

int main()

{

    struct Point p1;

 

    // Accessing members of point p1

    // No value is Initialized then the default value is considered. ie x=0 and y=1;

    cout << “x = ” << p1.x << “, y = ” << p1.y<<endl;

 

    // Initializing the value of y = 20;

    p1.y = 20;

    cout << “x = ” << p1.x << “, y = ” << p1.y;

    return 0;

}

Structures can be initialized using curly braces:

struct Point {

    int x, y;

};

 

int main()

{

    // A valid initialization. member x gets value 0 and y

    // gets value 1.  The order of declaration is followed.

    struct Point p1 = { 0, 1 };

}