0
Posted December 3, 2012 by Victor in C/C++ Programming
 
 

How C++ Structs Work

struct2
struct2

A structure refers to data elements that are grouped together using a single name. The data elements in a structure are called members and they can be composed of different data types and lengths. There is much similarity between the C++ classes and the C++ structures with the only difference being the fact that structure members have public access by default while class members are by default limited to private access.

Structures have taken over the place for arrays in terms of data storage and unlike arrays which had to be of a similar data type, the structures can store data from different data types. Once a structure has been defined, it automatically becomes a user defined data type and can be used in the same manner other data types like int, float, char are used.

Suppose we were dealing with student details in a university, there are many different data types that will be declared and used because we will need information such as the name, age, street, ID number and the like. The following example will be useful in knowing how structures are declared, called and used in C++s. To better understand structures, you can also refer to our How C++ classes work.


// example on structures
#include <iostream>
using namespace std;

     struct students //name of the structure
     {
         student_details (); //declaration of data types within the structure
         int student_phone;
         char student_guardian;
         academic_records();
     };

     //use functions found within a structure outside the structure as shown below

     students::student_details()
     {
         students listdetails;
         int student_ID ;
         cout << "Please Enter Student ID Number:\n\n:____";
         cin >> student_ID;

         // this part of the function needs student ID.
         // If Student_ID is incorrect an error message is prompted.
         //In this case the student ID is 11

         if (student_ID == 11)
         {
             cout << "\n\nVictor's Academic Records\n\n";
             // calls the function with the academic records for the student
             listdetails.academic_records ();
         }
         else
         {
             cout << "The ID you entered is not in our databases\n\n";
         }
     }

     // this is the function with the academic records for the specified student
     students::academic_records ()
     {
         cout << "\n\nMaths 78%\n";
         cout << "\n English 98%\n";
         cout << "\n Biology 100%\n\n";
     }

    int main ()
    {
        // creating the object of a structure within the main function so that
        //the data types in the structure can be used
        students listdetails;

        // calling the function student details that is found in the structure
        listdetails.student_details ();

        return 0;
     }


Victor