CyberArmy Academy | CyberArmy Services & Support | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Projects

[Library Index]

[View category: C++] [Discuss Article]

Practical C++ Part 8 : Structures

Article is yet to be rated
Author:      Rae
Submitted:      28-Apr-2007 19:41:03
Imported From:      The CyberArmy University (original author: rae)


Practical C++ Part 8 : Structures
Structures are a way of combining many different variables of different types under the same name. A general format of a structure is :-
struct <name> {

  type1 element1;
  type2 element2;
  type3 element3;
  
}<structure variable>;
Here <name> stands for the name you want to give to the structure, whereas <structure variable> is the variable type or object of the structure. Remember that it is not necessary to write the <structure variable> immediately after the definition of the structure. Let us take a program which shows the use of structures with the above mentioned concepts,
#include <iostream.h>
#include <conio.h>

struct database {
  int id;
  int age;
  float salary;
};

void main()
{
  clrscr();
  database person;

  person.age = 20;
  person.id = 123;
  person.salary = 8000;

  getch();
}
In the above code we make a structure called 'database' with three members - id, age and salary. We then define an object 'person' of the type 'database'. Notice how we assign the values to the different members using the dot (.) operator. The advantage of using structures is that it makes the program more modular. Structures can also be nested within one another, that is, a structure can have another structure as its data member.

There is also another similar concept called 'unions'. They are similar to structures except for the fact that all the variables defined in the structure share the same memory. When a union is declared the compiler allocates enough memory for the largest data-type in the union.

A lengthy discussion of structures or unions is not important in C++, as these concepts are more important to C. C++ uses 'classes' instead of structures, which we will see later on.

References :-

http://www.cplusplus.com

http://www.cprogramming.com/

Written by Rae

Member Of Knowledge Bank Tutorial Writers (#619)

Edited by NeorageX

This article was originally published by CyberArmy.net in the CyberArmy Library.

You must be logged in to vote on an article

About Us | Privacy Policy | Mission Statement | Help