Skip to main content

C++ User defined Data Types.

I had explained Built-in and Derived Data types in previous blogs.

Now, Let's resume our topic from User Defined Data types.

Simple definition - User defined data types are the data types which the User define by himself/herself.

We need these data types because there are certain cases when the pre-defined data types won't help us, e.g. think of a list, which contain every information about every particular student learning in a school. Like Student name, Student IDs, Student class, Student section etc. You can think of using arrays, but arrays can only contain one field of data of built-in datatypes like int, char etc. Which is not sufficient.

Now, We will discuss the following topics - 

  1. Class.
  2. Structures.
  3. Enumeration.
  4. Union.
So, let's start our discussion.

Classes


Class is a data type present in C++, but not in C.
Classes can be considered as a mechanism that allows us to create new types(of data), and we can declare and use objects of that type.
A class definition consists of two parts, the class head, made of the class keyword and the class name, and the class body, enclosed by curly braces and terminated with a semicolon (;).
Let's see in the code snippet.

1
2
3
4
5
6
7
8
9
class Class_Name {
    // Class body starts here
    Access Specifiers:

    Data Members;

    Member functions(){;}

}; // semi-colon is important here.

Now, let's see it line by line. 

  • In Line 1, We have class Class_Name, here class is keyword ( keywords are words that are reserved by the c++ compiler, with some specific meaning), class tells us that, we are defining/ declaring a class. Class_Name is an identifier (it represents the new data types) and it is the name that the user wants to give to the class.
  • In Line 3, We have Access Specifiers, Access specifiers specifies that who can access the members of our class like data in our class and function in our class etc. There are three access specifiers that we can use in our class - 
    • private.
    • protected.
    • public.
  • Data Members - Data members is the data that our class contains, taking student list example - the data is equivalent to the Names, IDs etc.
  • Member functions - For modifying and getting some useful results from the data, we need some function to act upon that data and those functions are called Member functions. (Functions present inside a class are called member functions, and other function are simply called function).
A simple class example.

#include<iostream>
using namespace std;

class YourCppTutor{
    public:
        void What_are_we_doing_here()
        {
            cout <<"We are learning C++" << endl;
        }
};
int main()
{
    YourCppTutor object1;

    YourCppTutor *object2;

    object1.What_are_we_doing_here();
    
    object2->What_are_we_doing_here();


    return 0;
}

Here, I defined a class with Identifier YourCppTutor and inside class, I defined a member function named "What_are_we_doing_here()" which is taking no parameter and is of type void i.e. it not returning anything to the calling function.
In the main function, I have created one object (object1) of type YourCppTutor and One pointer to object(object2) of type YourCppTutor. We use dot operator (.) to access member objects of class through class Object, and similarly We use arrow (->) operator to access member objects of a class through a pointer to class object.

We, will talk about about Definition of functions, Initialization list, Access specifiers, inheritance, polymorphism etc. in greater depth with examples in upcoming slides.

Structures

Structure is a user-defined data type present in both C and C++. The structure can be considered as a group of some data.
Let's see if we want to create a list of students which should have their names, their IDs, Classes and sections. We can create a structure like this.

#include<iostream>
#include<cstring>
using namespace std;

struct Students
{
    char name[20];    // Unlike classes we can't initialize any data member within structure.
    int ID;
    char Class[30];
    char Section;
};

void Print(struct Students x)           // Function for printing student information
{
    cout << "Student name is : " << x.name << endl;
    cout << "Student Id is : " << x.ID << endl;
    cout << "Students studies in class " << x.Class << " and section is " << x.Section << endl;
}

int main()
{
    struct Students first;
    strcpy(first.name, "JOHN");
    first.ID = 1;
    strcpy(first.Class, "Computer Science");
    first.Section = 'B';

    Print(first);

    /*
    Another and simple way of initializing first is to pass RValues like an array
    struct Students first = {"JOHN", 1, "Computer Science", 'B'};
    */
    
    return 0;
}

See output here.

Each Member of a structure has it's own memory space and all this memory spaces are included in the Students, For, clarity you can think of Students structure as a Universal Set, while the members can be considered as Subsets of universal Set and No set intersects with each other.

In the above example you must have noticed three things

  1. Every time we write our user-defined type i.e. Students, we write struct in front of it. Which is a necessity.
  2. In structures we can use any type of data as we want. and combine them to make a single block of structure.
  3. We accessed member objects with dot operator(particularly data members in this example), the reason being first is not a pointer.
We will use Structure in future discussions too.

Enumeration

Enumeration is also a group of data under a single name, but enumeration is little different than other user-defined data types. It is used to assign some integral code to the objects.
To understand it, you can consider the following example -
Suppose, you are writing some code for your application, Now think of a point where you need to implement a menu, Now, everyone knows a menu contains some operations/tasks to perform, Now, if you are familiar with real application, you must have seen that in menu there are some kind of sequence of characters which is often the name of the task we can perform using that option.
Now in computer if someone click on some option, you must know that which option is that to perform it successfully and for that you will compare these sequence of characters with your sequence of characters to match and identify which option to perform. Which is little tedious, as you will compare every character by character with your string and find the task in the final step. Suppose if the option name is too long than it will take some time. Now, here the Enumeration play its role, It provides some integral constant to those names and whenever someone click some option the integral value will be evaluated which will obviously be very fast. 
Let's see a sample program.
 
#include<iostream>
using namespace std;

enum Menu{      // enum is keyword and Menu is an identifier
    Open,
    Close,
    New,
    Edit,
    Cut,
    Paste
};

int main()
{
    Menu task = Open;           // Remember any object of Menu type can only take values defined in Menu
    cout << "Task has value : " << task << endl;       // Defaul Value Start from 0;
}

See output here.
You can assign any value you want to these Menu tasks. see below program

#include<iostream>
using namespace std;

enum Menu{      // enum is keyword and Menu is an identifier
    Open=1,
    Close=0,
    New = 3,
    Edit = 7,
    Cut,
    Paste
};

int main()
{
    cout << "Open is : " << Open << endl;
    cout << "Close is : " << Close << endl;
    cout << "New is : " << New << endl;
    cout << "Edit is : " << Edit << endl;
    cout << "Cut is : " << Cut << endl;
    cout << "Paste is : " << Paste << endl;

    return 0;
}

You will get output something like this.
Open is : 1
Close is : 0
New is : 3
Edit is : 7
Cut is : 8
Paste is : 9

You can see that if you don't define any value by yourself the value of a member object will be one greater than the value of it's previous member object, Like "Cut" and "Paste" have.

Now, we come to last topic of our User-Defined Data type.

Union

Union is also like structure, i.e. Union is also a group of data and the data can be of different types.
But, the most important to note is that we can initialize only one member object at a time, and each member of the Union shares memory, which is opposite to structures(remember intersection example?).
let's understand through the same example, I am just replacing struct with union.

#include<iostream>
#include<cstring>
using namespace std;

union Students
{
    char name[20];
    int ID;
    char Class[30];
    char Section;
};

void Print(union Students x)           // Function for printing student information
{
    cout << "Student name is : " << x.name << endl;
    cout << "Student Id is : " << x.ID << endl;
    cout << "Students studies in class " << x.Class << " and section is " << x.Section << endl;
}

int main()
{
    union Students first;
    strcpy(first.name,"JOHN");  // Copying "JOHN" in name of first
    first.ID = 1;
    strcpy(first.Class, "Computer Science");    // Copying "Computer Science" in class
    first.Section = 'B';

    Print(first);
    
    return 0;
}

We will get output like this.

Student name is : Bomputer Science
Student Id is : 1886220098
Students studies in class Bomputer Science and section is B

The output we got is weird, isn't it. Actually, the reason behind this random output is something like this-

Due to sharing of memory, when one member object is initialized, it affects the value of other member objects which were previously initialized.

I will discuss One more User-defined data type, Typedef in future slides.

Stay tuned for the upcoming content. For any query leave a comment below.


click Subscribe at top to subscribe.

References -
  • Lippman, Stanley B. c++ primer 3rd edition(april 2, 1998).

Comments

Popular posts from this blog

Introduction to Computer Science.

 Before directly jumping deeply in c++, let's first start by creating the roots of computer science. In this post we will answer the following question. What is Computer and How it works? What is Program and Operating system? Low Level vs High Level Language? Compiler v/s Interpreter? By Knowing All these basic concepts You will be able to understand the upcoming more complex concepts easily. Let's start answering the above questions. What is Computer and How it works? What is computer? If I answer briefly,  what is computer?  then it is just a calculator used for doing simple calculations. If I have to answer where is computer used?, then I could probably say everywhere. We are surrounded by computer, for example mobile, smartwatches, and personal computer (obviously).  The below image is the first mechanical computer that we used for calculation.                                        Abacus How computer works? The computer's internal functionality is a whole separate bra

C-style strings vs String Class.

Here, we are going to learn about, what are C-Style Strings and what is String class . So, let's start by giving you the introduction. C-Style String is nothing but, an array of characters, and from the term array we can surely assume that these are static in size i.e. the size of these C-Style strings cannot be increased or decreased. String Class is a Built-in class that provide us much more functionality than C-Style String. C-STYLE STRINGS Before learning the String class, which is full-fledged feature of C++, we should rather start by taking a look at some important things about C-Style String. C-Style Strings are actually array of characters that are terminated by a null character "\0". If you are confused with, why null character? The reason is that, It helps us to define, upto which index we have some useful data present in our character array, and after null character there may or may not be some garbage values of characters. Let's first start by showing a

Algorithms, Pseduocodes and FlowCharts.

Some Basic Knowledge. C++ is a general purpose programming language, created by Bjarne Stroustrup and was firstly released in  1985. It is an extension to C language, Reason for that is if you are familiar with C language than you must be familiar with the fact that there are no classes, templates etc. present in C language. Due to which when classes are added to C language it is named as "C with Classes", but C++ is considered as default name now.  Extra thing to remember - In "C++" the symbol "++" after C is post increment symbol and therefore, "C++" means that In C additional features are added. Now, let's define, what are algorithms? Algorithms are nothing but set of rules that must be followed to accomplish some task. (Now, What that mean?😕) let's take an example of swapping two numbers, i.e. if a = 10 and b = 20 after swapping a = 20 and b = 10. How will you write the procedure for this?  (There are many such algorithms). Accordin