< Browse > Home / C++ / Blog article: Structs in C++

Structs in C++

March 26th, 2009 | No Comments | Posted in C++ by Diego

Overview of Structs

Structs allow to combine multiple data types as a single data type. Access to these data types within the structs are done through the fields (members) name.

Structs become useful when you need to create a data type that you will use multiple times, requires multiple data types to define it and requires no additional functionality such as what is found in classes.

Example of a Struct

In general, a Struct defines a new data type. Below is an example of a Student.

struct Student {
    string name;
    int sid;
    string ssn;
};


Below is an example of how to create a student, assign values to its members and how to access them as well.

Student fred;
   
fred.name = "Fred";
fred.sid = 86088121;
fred.ssn = "123-20-2345";

cout << "Student: " << fred.name << endl << "Sid: " << fred.sid
              << endl << "SSN: " << fred.ssn << endl;
 


The output of the above code is as below

Student: Fred
Sid: 86088121
SSN: 123-20-2345
 

Summary

The previous Struct was declared before the main declaration of a C++ program. As you may have noticed it proves useful when a new data type needs to be defined.



Leave a Reply |

Related Posts to Structs in C++

Leave a Reply