Topic :Data Structure (Struct) in C++: Defining | Initializing | Using

Introduction To C++ Structures:

A structure is a collection of one or more variable types. As we know, each element in an Array must be the same data type, and we must refer to the entire array by its name. Each element (Called a Member) in a structure can be a different data type. The structure is another user-defined data type which allows us to combine data items of different kinds.

Structure are used to represent a record, suppose we want to keep track of Our books in a library. We might want to track the following attributes about each book.


  • » Title:
    » Author:
    » Subject:
    » Book ID


There would be four Members in this Library Structure. After deciding on the Members, we must decide what data type each member is. The title Author and subject are character arrays, The Book ID is an integer and so on.



Member NameData Type
Title: Character Array of 25 Characters.
Author: Character Array of 20 Characters.
Subject: Character Array of 25 Characters.
Book ID: Array of Integers:


Each structure we define can have an associated structure name called a Structure tag. Structure tags are not required in most cases, but it is generally best to define one for each structure in Our program. The structure tag is not a variable name. Unlike array names, which reference the array as variables, a structure tag is simply a label for the structure's format.



Although both contain the term "Structure", Control Structure and Data Structure are very different. The Control structure sequence, selection, and loop describe the logical flow of a program's instructions. Data Structure is used to encapsulate separate related data fields.


Defining a Structure:

Structures are Syntactically defined with the word Struct. so, Struct is another keyword that cannot be used as variable name. Followed by the name of the structure. The data, contained in the structure, is defined in the curly braces. All the variables that we have been using can be part of a structure. For Example:



struct Structure_Tag 
{ 
 
   Data-Type1  Element1;
   Data-Type2  Element2;
   Data-Type3  Element3;
   .
   .
   Data-TypeN  ElementN; 
 
} Structure_Object;



The Semicolon after the closing curly brace in the struct definitions is important. Our program will not compile without it. Unfortunately, this semicolon is easy to forget, because when closing curly braces appear in other places in C++ programs. (For Example, at the end of function) they are seldom followed by a semicolon.



Structure_Tag is a name for the model of the structure type and the optional parameter Structure_Object is a valid identifier for structure object instantiations. Within curly brackets { } they are the types and their sub-identifiers corresponding to the elements that compose the structure.

We Need to Name Structure_Tag our self, using the same naming rules for variables. if we give the "CAR" structure a structure tag named "CAR", we are informing C++ that the tag called "CAR" looks like an character Arrays, followed by an Float, and character Array.



No Memory is reserved for structure tags. A structure tag is our own data type. C++ does not reserve Memory for the integer data type until we declare an integer variable, same like that C++ does not reserve memory for a structure until we declare a structure variable.



If the Structure definition includes the parameter CAR, that parameter becomes a valid type name equivalent to the structure. For Example:


Struct CAR 
{ 
   char  Name[ 30 ]; 
   char  Model[ 30 ];
   float Price;
};
 
 
CAR  BMW;
CAR  Mercedes;
CAR  Dodge, Audi;

We have first defined the structure model "CAR" with Three fields: Name, Model, and Price Having different data types. We have then used the name of the structure type "CAR" to declare four objects of that type: BMW, Mercedes, Dodge, and Audi. once Declared, "CAR" has become a New valid type Name like the fundamental int, char or short and we are able to declare objects (variables) of that type.

The Optional Field Structure_Object that can go at the end of the structure declaration serves to directly declare the object of the structure type. For Example, we can also declare the structure objects BMW, Mercedes, Dodge, Audi this way:



Struct CAR 
{ 
   char  Name [ 30 ]; 
   char  Model[ 30 ];
   float Price;
 
}  BMW, Mercedes, Dodge, Audi;


Moreover, in cases like the last one in which we took advantage of the declaration of the structure model to declare object of it, the parameter CAR becomes Optional. Although if structure tag ( CAR ) is not included it will not be possible to declare more objects of this same model later.



It is Important to clearly differentiate between what is a "Structure_Tag", and what is a "Structure_Object". Using the terms we used with variables, the Tag is the type, and the Object is the variable. We can instantiate many objects (variable) from a single Tag (type).



Initializing Structure Data:

We have Learnt how to define a structure and declare its variables. Now Let's see how can we put the values in its data members or how we can use structure. To Access any Member of a structure, we use Dot ( . ) Operator. The Dot Operator is coded as a period between the structure variable name and the structure member that we wish to access. We would use struct keyword to define variables of the structure type.

Once we have declared our some objects of a determined structure ( CAR ) we can Operate with the fields that form them. to do that we have to use a point ( . ) Inserted between the object name and the field name. For example, we could Operate with any of these elements as if they were standard variables of their respective types:



BMW.Name;
BMW.Model;
BMW.Price;
Mercedes.Name;
Mercedes.Model;
Mercedes.Price;
Dodge.Name;
Dodge.Model;
Dodge.Price;
Audi.Name;
Audi.Model;
Audi.Price;


Each one being of its corresponding data type: BMW.Name, name are of type char, BMW.Model are of type char, and BMW.Price are of type float. Let's have an simple example to Understand the concept of Structure.



/* Structure in C++: Struct: InfoBrother*/
 
#include<iostream>
#include<string>//Include "string" to use string function.
using namespace std;
 
//Data Structure Declare With Structure_tag "Car".
struct CAR 
{
    int name;
    int model;
    float price;
};
 
main()
{
    struct CAR car; //Creating an Structure_object:
 
    cout<<" Enter the Name of Car: ";
    getline(cin, car.name);
    cout<<" Enter the Model of Car: ";
    getline(cin, car.model);
    cout<<" Enter the Price of Car in $: ";
    cin>>car.price;
 
    cout<<" \n\nCar Information: "<<endl;
    cout<<"Car Name: "  <<car.name<<endl;
    cout<<"Car Model: " <<car.model<<endl;
    cout<<"Car Price: $"<<car.price<<endl;
 
    return 0;
}

The Example shows how we can use the elements of a structure and the structure itself as normal variables. For example, car.name is a valid variables of type string, and car.Price is a valid type of float. Notice that car also treated as valid variables of types CAR. One of the most important advantages of structure is that we can refer either to their elements individually or the entire structure as a block.

Structures are a feature used very often to build databases, specially if we consider the possibility of building arrays of them.



/*Structure Array - InfoBrother*/
 
#include<iostream>
#include<string>//Required for string Function.
#include<cstdlib>//Required for clear Screen Function.
 
using namespace std;
#define count 5//Size of Array:
 
void getData(); //Function Prototype:
void showData(); //Function Prototype:
 
struct BOOKS //Structure Declared:
{
	char bookName[50];
	char authorName[50];
	int year;
 
} book[count]; //structure_Object Creation.
 
main()
{
    cout<<"============== MY FAVORITE BOOKS =============="<<endl;
    cout<<" \n=> Enter your Five Favorite Books Detail: "<<endl;
    getData();
    showData();
    return 0;
}
 
void getData() //Function Definition.
{
    for(int i=1; i<=count;i++)
    {
        cout<<"\n Enter Name of Book # "<<i<<": " ;
        cin.getline(book[i].bookName,50);
        cout<<" Enter Author Name: ";
        cin.getline(book[i].authorName,50);
        cout<<" Enter Published Year of Book: ";
        cin>>book[i].year;
        cin.ignore();
    }
}
 
void showData() //Function Defination.
{
    system("cls"); //Clear Screen Function.
    cout<<" \n\n=============== Favorite Books Record:=============== "<<endl;
    cout<<"\n\n";
 
    for(int i=1; i<=count; i++)
    {
        cout<<i<<") Book Name: "<<book[i].bookName<< " ( " 
	       <<book[i].year<<" ) "<<endl;
 
        cout<<" Author Name: "<<book[i].authorName<<endl;
        cout<<"\n";
    }
}


The Typedef Keyword:

This is an Easier way to define structs or we could "Alias" types we create. within the iostream library, the creators of C++ have used typesdefs to provide aliases for the template Names that begin with basic and the underscore. C++ Allows us to define new data type names with the typedef keyword. When we use typedef, we are not actually creating a new data type, but rather defining a new Name for an existing type. This process can help make machine-dependent programs more portable; only the typedef statements have to be changed. it also helps us self-document our code by allowing descriptive names for the standard data types. The Typedefs istream, ostream, and iostream are used for character input and output. The General form of the typedef statement is:


typedef type name;


For structure the example is:


typedef struct 
{ 
   char bookName[ 50 ];
   char authorName[ 50 ];
   int Year ; 
 
} Books;


Now, we can use Books directly to define variables of Books type without using Struct keyword. Following is the Example:


Books Book1 , Book2 ;


We can use Typedef keyword for non-structs as well as follows:


typedef int * Name; 
Name x, y, z ;


X, y, and Z are all pointers to ints;



In C, there was an structure but now in C++ there is an class instead of structure. In C++, a structure is same as class except the following differences:
» Member of a class are private by default and Members of struct are public by default.
» When deriving a struct from a Class/Struct, default access-specifier for a base class/struct is public. and when deriving a class, default access specifier is private.








I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement