C++ Structures

C++ structures provides a way to store many different values in variables of potentially different types under the same name. It makes the program more modular, which is easier to modify because its design makes things more compact. Structures are useful whenever a lot of data needs to be grouped together e.g. they can be used to hold records from a database or to store information about contacts in an address book. In the contacts example, a struct will hold all of the information about a single contact for example name, address, phone number etc.

Defining structures

struct structName {

member definition;
member definition;

} structureVariables;

structName is the name of the entire type of structure which is optional and members are the variables within the struct, structureVariables are one or more structure variables which is optional.

struct Contacts {

char fristName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;

}contact;

Accessing Structure Members

The dot (.) operator is used to access any member of a structure. Dot operator is used between the structure variable name and the structure member that we are going to access. struct keyword is used to define variables of structure type.

#include <iostream>
#include <cstring>

using namespace std;

struct Contacts {

char firstName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;

};

int main( ) {

//Declaring Contact1 of type Contact
struct Contacts Contact1;

strcpy( Contact1.firstName, “Scott”);
strcpy( Contact1.lastName, “Tiger”);
strcpy( Contact1.emailAddress, “tiger@tutorialsgenie.com”);
Contact1.age = 28;
Contact1.contact_id = 1071;

//Printing Contacts
cout << “Contact1 firstName : ” << Contact1.firstName <<endl;
cout << “Contact1 lastName : ” << Contact1.lastName <<endl;
cout << “Contact1 emailAddress : ” << Contact1.emailAddress <<endl;
cout << “Contact1 age : ” << Contact1.age <<endl;
cout << “Contact1 id : ” << Contact1.contact_id <<endl;

return 0;

}

Output of the above program will be

Contact1 firstName : Scott
Contact1 lastName : Tiger
Contact1 emailAddress : tiger@tutorialsgenie.com
Contact1 age : 28
Contact1 id : 1071

typedef Keyword

The typedef Keyword can be used to define structures.

typedef struct {

char firstName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;

}Contacts;

Now Contacts can be used to directly define variables of Contacts type without using struct keyword.

One thought on “C++ Structures

  1. derp Reply

    Structure name is sufficient in variable definition in C++, it’s not required to use typedef of struct keyword as in plain C. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *