User Defined Data Types of C++ | enumerated data type in C++ | typedef in C++

User Defined Data Types of C++
You must first complete Constant in C++ | Literals in C++  before viewing this Lesson

User Defined Data Types of C++ | enumerated data type in C++ | typedef in C++



What is Data type ?

Data type gives the type and range of values that can be stored in a variable in C++. Different types of data types are

User Defined Data Types of C++

Different categories of user defined data types in C++ are:

 i. Structure

Structure is a collection of multiple variables of different data types under a single name. Structure members automatically become part of structure variable. We can use keyword struct to define a structure.

Example:

struct emp
{
int id;
char ename[10];
};

ii. Union

Union looks like a structure as It also contains more than one variable in it. Union is preferred where we need to use only one of members of a union at a time. We need to use keyword union to define a union in C++.

Example:        

union emp { int id; char ename[20]; };

iii. class

Class is a user defined data type that can contain variables called data members and functions called member functions of the class.

Example

class student
{
int rollno;
char name[20];
public:
void read()
{
 cout<<”\nEnter rollno=”;
 cin>>rollno;
 cout<<”\nEnter name=”;
 gets(name);
}
void show()
{
 cout<<”\nRollno=”<<rollno;
 cout<<”\nName=”<<name;
}
};

iv. typedef

typedef is a keyword to give a new name to an existing data type.

Example:

typedef  double Amount ;

In this example, data type double is named as Amount.

Amount first, second;

Above statement will create two variables first and second of double data type.

v. enum (Enumerated data type in C++)

enum is known as enumerated data type. It creates a sequence of named constants that have consecutive integer values starting with 0.

Example 1 :

enum day{sunday,monday,tuesday,wednesday,thursday,friday,saturday};

In this example, day is the enumerated data type  containing values sunday, monday, tuesday, wednesday, thursday, friday, saturday

In this list, sunday is the named constant containing default value 0, monday contains 1, tuesday contains 2 and so on.

Example 2:

enum day{sunday=1,monday,tuesday,wednesday,thursday,friday,saturday};

In this list, sunday is the named constant containing value 1, monday contains 2, tuesday contains 3 and so on.

//Program to demonstrate the use of enum

#include<iostream>
using namespace std;
int  main()
{
enum day{sunday,monday,tuesday,wednesday,thursday,friday,saturday};
day d
d=wednesday;
cout<<”d=”<<d;
return(0); 
}

Output:

d=3



Spread the love
Lesson tags: Enumerated data type in C++, typedef in C++, User Defined Data Types of C++, What is a Data type in C++
Back to: C++ Programming Notes
Spread the love