Complete Computer Knowledge Portal

Wednesday, July 17, 2013

User Defined Data Types in C++

The third type of data type in C++ is user defined. Following are some user defined data types:
Structure:  Collection of data elements grouped under one name is called Structure. Different data elements are called members and can have different data type of different length.
Declaration
Struct Student
{
Int roll_no;
Float marks;
} BA, BSC, BCOM;
In this example Student is declared as Structure with members roll_no and marks. BA, BSC, BCOM are the objects of structure Student. Here roll_no is declared as integer and marks as float, which are fundamental data types.

Class: Extended version of Structure is called Class. Structure holds only data whereas class can hold both data and functions. Another concept of access specifier is also added to it which uses three keywords Public, Private, Protected. Access Specifier modifies access rights as:
Public: Public members can be accessed anywhere where object is visible.
Private: Private members can be accessed only by other members of same class or by their friend functions.
Protected: Protected members can be accessed by other members or same class, their friend functions and by elements of derived classes of same class.
Declaration
Class addition
{
Int a, b;
Public:
void values(Int, Int);
}A;
Here addition is a class with one object A. Here a and b are private members of class whereas function values is a public function.

Union: It is a memory location that is shared by two or more variables of different types. Keyword union is used for declaring and creating union. Consider the following example:
Union div
{
Int a;
char c;
};
Union div def;
In this example div is a Union with two variables a and c. Def is the union object.

Enumeration:  This data type consists of named values to represent integral constants which are called enumeration constants. Here are some examples to define enumeration constants:

enum colors { Red, Green, blue, white, Orange };
   /*         0      1      2      3     4         */

enum colors { Red=1, Green, blue, white, Orange };
   /*          1       2      3     4      5       */

enum colors { Red, Green=9, blue, white=15, Orange };
   /*          0     9        10      15      16       */

It provides the way to associate the same integer with two different enumeration constants.

enum sound { Play, Pause=5, Go, Forward, Backward=6 };
   /*          0      5     6     7          6       */


No comments:

Post a Comment