Table of contents
User-Defined Derived Data types There are some derived data types that are defined by the user. These are class , structure , union and enumeration.
Class
- A class represents a group of similar objects. To represent classes , it offers a user-defined data type called class.
- Once a class has been defined , objects belonging to that class can easily be created.
- Class keyword is used to define a class.
- Class can store different data members and member functions of different data types.
- In order to access members of a class , class object is needed.
- By default all members are private in class.
Below given code fragment is a example of class ->
class student { //student class
public:
int age; //data members
int rollno;
void display() //member function
{
cout<<"Age"<<age;
cout<<"Roll number"<<rollno;
}
};
Structure
A structure is a collection of variables of different types (different data types) referenced under one name, providing a convenient means of keeping related information together.
struct keyword is used in defining a structure.
By default all members are public in structure.
Below given code fragment is a example of structure ->
struct student { //student structure
int age; //data members
int rollno;
};
Union
A Union is a memory location that is shared by two or more different variables generally of different types at different times.
Defining a union is similar to defining a structure.
union keyword is used for defining a union.
Below given code fragment is a example of union ->
union share {
int i;
char ch;
}; // both i and ch share the same memory allocation.
Enumeration
An alternative method for naming integer constants is often more convenient than const. This can be achieved by creating enumeration.
enum keyword is used for creating enumeration.
Below given code fragment is a example of enumeration ->
enum { start,pause,go };
//defines three integer constants and assigns values to them
//enum values are by default assigned increasing from 0.
//above declaration is equivalent for writing const int start=0,const int pause=1,const int go=2.