Implementation of User-Defined data using Struct in C++


There are two kind group of data type that needed to reserve amount memory, primitive data and user-defined data. Primitive data just like Int (4 byte), Char (1 byte), Double (8 byte) and so on. But what about we construct our custom data types, like a new data type that contains Int and Char? Then this is called user-defined data.

Basically, we just gathering two or more primitive data into one new data type. For instance, first we have Customer and Grade variable:

1
2
int customer;
string address;

Because Customer and Grade tight each other, we construct a new data type called “user” that contains Customer and Grade. To do this step in C++, we use “struct” :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<string>
using namespace std;

struct data_t {
    int customer;
    char grade;
} user;

int main()
{
    user.customer = 1;
    user.grade = "A";
    cout << insurance.customer;
    cout << insurance.grade;

    return 0;
}

Now, we have an example of user-defined data called “user”. In memory level, it will reserve amount of memory that summary of this two primitive data type which int is 4 byte and char is 1 byte. In another programming language like Pascal, this kind of data called as “record”.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.