Struct

 https://www.w3schools.com/cpp/cpp_structs.asp

C++ Structures

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, string, bool, etc.).


Create a Structure

To create a structure, use the struct keyword and declare each of its members inside curly braces.

After the declaration, specify the name of the structure variable (myStructure in the example below):

struct {             // Structure declaration
  int myNum;         // Member (int variable)
  string myString;   // Member (string variable)
myStructure;       // Structure variable

Access Structure Members

To access members of a structure, use the dot syntax (.):

Example

Assign data to members of a structure and print it:

// Create a structure variable called myStructure
struct {
  int myNum;
  string myString;
} myStructure;

// Assign values to members of myStructure
myStructure.myNum = 1;
myStructure.myString = "Hello World!";

// Print members of myStructure
cout << myStructure.myNum << "\n";
cout << myStructure.myString << "\n";
Try it Yourself »

One Structure in Multiple Variables

You can use a comma (,) to use one structure in many variables:

struct {
  int myNum;
  string myString;
} myStruct1, myStruct2, myStruct3; // Multiple structure variables separated with commas

This example shows how to use a structure in two different variables:

Example

Use one structure to represent two cars:

struct {
  string brand;
  string model;
  int year;
} myCar1, myCar2; // We can add variables by separating them with a comma here

// Put data into the first structure
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;

// Put data into the second structure
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;

// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
Try it Yourself »

Named Structures

By giving a name to the structure, you can treat it as a data type. This means that you can create variables with this structure anywhere in the program at any time.

To create a named structure, put the name of the structure right after the struct keyword:

struct myDataType { // This structure is named "myDataType"
  int myNum;
  string myString;
};

To declare a variable that uses the structure, use the name of the structure as the data type of the variable:

myDataType myVar;

Example

Use one structure to represent two cars:

// Declare a structure named "car"
struct car {
  string brand;
  string model;
  int year;
};

int main() {
  // Create a car structure and store it in myCar1;
  car myCar1;
  myCar1.brand = "BMW";
  myCar1.model = "X5";
  myCar1.year = 1999;

  // Create another car structure and store it in myCar2;
  car myCar2;
  myCar2.brand = "Ford";
  myCar2.model = "Mustang";
  myCar2.year = 1969;
 
  // Print the structure members
  cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
  cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
 
  return 0;
}
Try it Yourself »

What is a structure?

A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.
For example:
Suppose you need to store information about someone, their name, citizenship, and age. You can create variables like name, citizenship, and age to store the data separately.
However, you may need to store information about many persons in the future. It means variables for different individuals will be created. For example, name1, citizenship1, age1 etc. To avoid this, it’s better to create a struct.

 


When to use a Structure?

· Use a struct when you need to store elements of different data types under one data type.
· C++ structs are a value type rather than being a reference type. Use a struct if you don’t intend to modify your data after creation


How to create a structure?


The ‘struct’ keyword is used to create a structure. The general syntax to create a structure is as shown below:

struct structureName {
member1;
member2;
member3;
.
memberN;
};

Structures in C++ can contain two types of members:

· Data Member: These members are normal C++ variables. We can create a structure with variables of different data types in C++.
· Member Functions: These members are normal C++ functions. Along with variables, we can also include functions inside a structure declaration.

Example:

// Data Members

int roll;
int age;
int marks;

// Member Functions

void printDetails()
{
cout<<"Roll = "<<roll<<"\n";
cout<<"Age = "<<age<<"\n";
cout<<"Marks = "<<marks;
}

How to declare structure variables?


A structure variable can either be declared with structure declaration or as a separate declaration like basic types.

// 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
}

How to initialize structure members?
Structure members cannot be initialized with declaration. For example the following C program fails in compilation.
But is considered correct in C++11 and above.
struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};
The reason for above error is simple, when a datatype is declared, no memory is allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized with declaration in C++. For Example the following C++ program Executes Successfully without throwing any Error.


// 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;
}

// This code is contributed by Samyak Jain

x=0, y=1
x=0, y=20
Structure members can be initialized using curly braces ‘{}’. For example, following is a valid initialization.

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 };
}

How to access structure elements?
Structure members are accessed using dot (.) operator.

#include <iostream>
using namespace std;
struct Point {
int x, y;
};

int main()
{
struct Point p1 = { 0, 1 };
// Accessing members of point p1
p1.x = 20;
cout << "x = " << p1.x << ", y = " << p1.y;
return 0;
}

Output
x = 20, y = 1


What is an array of structures?

Like other primitive data types, we can create an array of structures.

#include <iostream>
using namespace std;
struct Point {
int x, y;
};

int main()
{
// Create an array of structures
struct Point arr[10];
// Access array members
arr[0].x = 10;
arr[0].y = 20;
cout << arr[0].x << " " << arr[0].y;
return 0;
}

Output
10 20


What is a structure pointer?
Like primitive types, we can have pointer to a structure. If we have a pointer to structure, members are accessed using arrow ( -> ) operator instead of the dot (.) operator.

#include <iostream>
using namespace std;
struct Point {
int x, y;
};

int main()
{
struct Point p1 = { 1, 2 };
// p2 is a pointer to structure p1
struct Point* p2 = &p1;
// Accessing structure members using
// structure pointer
cout << p2->x << " " << p2->y;
return 0;
}

Output
1 2


What is structure member alignment?

See https://www.geeksforgeeks.org/structure-member-alignment-padding-and-data-packing/
In C++, a structure is the same as a class except for a few differences. The most important of them is security. A Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details.


Structure vs class in C++

In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whoever uses it in code, while a class by default hides all its implementation details and will therefore by default prevent the programmer from accessing them. The following table summarizes all of the fundamental differences.

 

Class

Structure

Members of a class are private by default.

Members of a structure are public by default. 

Member classes/structures of a class are private by default.

Member classes/structures of a structure are public by default.

It is declared using the class keyword.

It is declared using the struct keyword.

It is normally used for data abstraction and further inheritance.

It is normally used for the grouping of data



Some examples that elaborate on these differences:

1) Members of a class are private by default and members of a structure are public by default.
For example, program 1 fails in compilation but program 2 works fine,

Program 1:
// C++ Program to demonstrate that
// Members of a class are private
// by default
using namespace std;
class Test {
// x is private
int x;
};

int main()
{
Test t;
t.x = 20; // compiler error because x  is private
return t.x;
}

 
 Output:

prog.cpp: In function ‘int main()’:

prog.cpp:8:9: error: ‘int Test::x’ is private

    int x;

        ^

prog.cpp:13:7: error: within this context

    t.x = 20;

      ^

Program 2:
// C++ Program to demonstrate that
// members of a structure are public
// by default.
#include <iostream>
struct Test {
// x is public
int x;
};

int main()
{
Test t;
t.x = 20;
// works fine because x is public
std::cout << t.x;
}
Output
20 
 
2) A class is declared using the class keyword, and a structure is declared using the struct keyword.  Syntax: 

class ClassName {
private:
member1;
member2;
public:
member3;
.
memberN;
};

Syntax:

struct StructureName {
member1;
member2;
.
memberN;
};

3) Inheritance is possible with classes, and with structures.

For example, programs 3 and 4 work fine.
Program 3:
// C++ program to demonstrate
// inheritance with classes.

#include <iostream>
using namespace std;
// Base class
class Parent {
public:
int x;
};
// Subclass inheriting from
// base class (Parent).
class Child : public Parent {
public:
int y;
};

int main()
{
Child obj1;
// An object of class Child has
// all data members and member
// functions of class Parent.
obj1.y = 7;
obj1.x = 91;
cout << obj1.y << endl;
cout << obj1.x << endl;
return 0;
}
Output
7
91 

Program 4:
// C++ program to demonstrate
// inheritance with structures.
#include <iostream>
using namespace std;
struct Base {
public:
int x;
};

// is equivalent to
// struct Derived : public Base {}
struct Derived : Base {
public:
int y;
};

int main()
{
Derived d;
// Works fine because inheritance
// is public.
d.x = 20;
cout << d.x;
cin.get();
return 0;
}

Output
20

https://www.guru99.com/cpp-structures.html



Code Explanation:

  1. Include the iostream header file in our program to use the functions defined in it.
  2. Include the std namespace to use its classes without calling it.
  3. Create a struct named Person.
  4. The beginning of the struct body.
  5. Create a struct member named citizenship of type integer.
  6. Create a struct member named age of type integer.
  7. End of the struct body.
  8. Call the main() function. The program logic should be added within the body of this function.
  9. Create an instance of the struct Person and giving it the name p.
  10. Set the value of struct member citizenship to 1.
  11. Set the value of struct member age to 27.
  12. Print the value of the struct member citizenship on the console alongside some other text.
  13. Print the value of the struct member age on the console alongside some other text.
  14. The program should return a value if it runs successfully.
  15. End of the main() function.

 


No comments: