9.3.14

Exercise : Classes and Objects with Constructor-cum-Destructor

Class and Objects

Constructor and Destructor with Methods and properties


A class is a user defined data type like a structure or a union. A class consists of data variables and functions. These variables and functions are called members of the class.  The variables are called data members and functions are called member functions. The member functions are also called methods. The data members are called properties of the class. An object is the instance of the class. An object is like a compound variable of the user defined type. It links both code and data. Within the object, members of the class can be public or private to the object. The declaration of a class is syntactically same as structure. The class is declared using keyword class. The general form of the declaration of the class is:-

class class_name
{
             
            access_specifier:
                        data functions
            access_specifier:
                        data functions

} object_list;

The object_list is optional. The object_list is used to declare objects of the class. The class_name is the name of the class.  The access_specifier can either public, private or protected. The members of the class by default are private to the class. If the access_specifier is private then members of the class are not accessible outside the class. If the access_specifier is public then members of the class can be accessed from outside the class. The protected access_specifier is needed at the time of inheritance. The members can be accessed using an object’s name, a dot operator and name of the member. Here is a program which shows how classes and objects are created.

#include<iostream>
using namespace std;

class cube
{
            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }
};
                       
int main()
{
            double volume1=0;
            cube c1,c2;
            cout << "Enter the lenght of the cube" << endl;
            cin >> c1.side;
            cout << "The volume of the cube is : " << c1.volume() << endl;
            c2.side=c1.side +2;
            cout << "The volume of the second cube is : " << c2.volume() << endl;
            return(0);
}

The result of the program is:-

class

The program consists of a class cube which has data member side of type double and member function which calculates the volume of the cube. The statement

            class cube

declares a class cube. The statements

            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }

declare that access_specifier is public for data member side and member function volume. These members can be accessed from the other parts of the program. The statement

            cube c1,c2;

declares two objects c1 and c2 of type cube. The statement

            cin >> c1.side;

access the data member of the cube. The member is accessed by specifying the name of the object as c1 then dot operator and then name of the variable side. The length entered by the user is stored in c1.side. In the statement

            cout << "The volume of the cube is : " << c1.volume() << endl;

c1.volume() calls the member function volume which returns the volume of the cube of side whose length is entered by the user. The statement

            c2.side=c1.side +2;

equates the side of object c2 to side of object c1 increased by 2.  The objects c2 and c1 are different. The statement

            cout << "The volume of the second cube is : " << c2.volume() << endl;

displays the volume of second object c2.

Constructor and Destructor:


Constructors are used in order to initialize the objects. A constructor is a special kind of a function which is the member of the class. The name of the constructor is same as name of the class. A constructor is automatically called when object is created. A constructor does not have a return type.

A default constructor is a constructor with no parameters. If no constructor is defined by the user then compiler supplies the default constructor. Once the constructor is defined by the user then compiler does not supply default constructor and then user is responsible for defining default constructor. 

A destructor is the complement of the constructor. It is used to destroy the objects. The objects are destroyed in order to deallocate the memory occupied by them. The name of the destructor is same as the name of the constructor as is preceded by a tilt operator ‘~’. A destructor for objects is executed in the reverse order of the constructor functions.

Here is a program which shows how constructors and destructors are used.

#include<iostream>
using namespace std;

class cube
{
            public:
                        double side;
                        double volume()
                        {
                                    return(side*side*side);
                        }
                        cube(double side1)
                        {
                                    cout << "A constructor is called" << endl;
                                    side=side1;
                        }
                        cube()
                        {
                                    cout << "A default constructor is called " << endl;
                        }
                        ~cube()
                        {
                                    cout << "Destructing " << side << endl;
                        }
};
                       
int main()
{
            cube c1(2.34);
            cube c2;
            cout << "The side of the cube is: " << c1.side << endl;
            cout << "The volume of the first cube is : " << c1.volume() << endl;
            cout << "Enter the length of the second cube : " ;
            cin >> c2.side;
            cout << "The volume of second cube is : " << c2.volume() << endl;
            return(0);
}

The result of the program is:-

constructor

The statement
                       
            cube(double side1)
            {         
                                    cout << "A constructor is called" << endl;
                                    side=side1;
            }
declares the constructor of the class cube. The name of the constructor is same as the name of the class. There is no return type in the constructor. It will initialize the value of data member side. The statement

                       
cube()
                        {
                                    cout << "A default constructor is called " << endl;
                        }

declares a default constructor. The statement

                         ~cube()
                        {
                                    cout << "Destructing " << side << endl;
                        }

declares a destructor to deallocate the objects. The statement

            cube c1(2.34);

creates an object c1 of type cube. A constructor is automatically called and initializes the data member side with value 2.34. The statement

                        cube c2;

creates an object of type c2. When object c2 is created a default constructor is called and the message will be printed. The statements

            cout << "The side of the cube is: " << c1.side << endl;
            cout << "The volume of the first cube is : " << c1.volume() << endl;

displays the side and volume of the cube where side has value 2.34. The statement

            cin >> c2.side;

will set the value of the side of the object c2 as entered by the user. At the end of the program objects are deallocated in the reverse order in which constructors are called. First object c2 is deallocated whose side is 2.5 and then object c1 is deallocated whose side is 2.34.

Advantage of the classes:-

It provides protection to the data. The members of the class are by default private to the class while the members of the structure are public. OOP features allow programmer to easily handle complex problems and multi file projects. They help in modeling real world objects such as bank accounts and their related transactions.

Exercise-1:  One steps through integer points of the straight line. The length of a step must be non negative and can be by one bigger than, equal to, or by one smaller than the length of the previous step. What is the minimum number of steps in order to get from x to y ? The length of the f irst and the last step must be 1. View Details

Exercise-2: Some operators checks about the relationship between two values and these operators are called relational operators.
Given two numerical values your job is just to nd out the relationship between them that is
(i) First one is greater than the second
(ii) First one is less than the second or
(iii) First and second one is equal. 

View Details 

Functions in C++


                                                Functions

Before reading this tutorial you should have knowledge of pointers.

Functions are building blocks of the programs. They make the programs more modular and easy to read and manage. All C++ programs must contain the function main( ). The execution of the program starts from the function main( ). A C++ program can contain any number of functions according to the needs. The general form of the function is: -

return_type  function_name(parameter list)
{
            body of the function

}

The function of consists of two parts function header and function body. The function header is:-

            return_type   function_name(parameter list)

The return_type specifies the type of the data the function returns. The return_type can be void which means function does not return any data type. The function_name is the name of the function. The name of the function should begin with the alphabet or underscore. The parameter list consists of variables separated with comma along with their data types. The parameter list could be empty which means the function do not contain any parameters. The parameter list should contain both data type and name of the variable. For example,

            int factorial(int n, float j)

is the function header of the function factorial. The return type is of integer which means function should return data of type integer. The parameter list contains two variables n and j of type integer and float respectively. The body of the function performs the computations.



Function Declaration

A function declaration is made by declaring the return type of the function, name of the function and the data types of the parameters of the function.  A function declaration is same as the declaration of the variable. The function declaration is always terminated by the semicolon. A call to the function cannot be made unless it is declared. The general form of the declaration is:-

return_type function_name(parameter list);

For example function declaration can be
            int factorial(int n1,float j1);

The variables name need not be same as the variables of parameter list of the function. Another method can be
           
int factorial(int , float);

The variables in the function declaration can be optional but data types are necessary.

Function Arguments

The information is transferred to the function by the means of arguments when a call to a function is made.  Arguments contain the actual value which is to be passed to the function when it is called.  The sequence of the arguments in the call of the function should be same as the sequence of the parameters in the parameter list of the declaration of the function. The data types of the arguments should correspond with the data types of the parameters. When a function call is made arguments replace the parameters of the function.

The Return Statement and Return values

A return statement is used to exit from the function where it is. It returns the execution of the program to the point where the function call was made. It returns a value to the calling code. The general form of the return statement is:-

return expression;

The expression evaluates to a value which has type same as the return type specified in the function declaration. For example the statement,

            return(n);

is the return statement of the factorial function. The type of variable n should be integer as specified in the declaration of the factorial function. If a function has return type as void then return statement does not contain any expression. It is written as:-

            return; 

The function with return type as void can ignore the return statement. The closing braces at the end indicate the exit of the function. Here is a program which illustrates the working of functions.

#include<iostream>
using namespace std;
int factorial(int n);

int main ()
{
            int n1,fact;
            cout <<"Enter the number whose factorial has to be calculated" <<  endl;
            cin >> n1;
            fact=factorial(n1);
            cout << "The factorial of " << n1 << "  is : " << fact << endl;
            return(0);
           
}
int factorial(int n)
{
            int i=0,fact=1;
            if(n<=1)
            {
                        return(1);
            }
            else
            {
                        for(i=1;i<=n;i++)
                        {
                                    fact=fact*i;
                        }
                        return(fact);
            }
}

The result of the program is:-


The function factorial calculates the factorial of the number entered by the user. If the number is less than or equal to 1 then function returns 1 else it returns the factorial of the number. The statement

            int factorial(int n);

is a declaration of the function. The return type is of integer. The parameter list consists of one data type which is integer. The statement

            cout <<"Enter the number whose factorial has to be calculated" <<  endl;
            cin >> n1;
makes the user enter the number whose factorial is to be calculated. The variable n1 stores the number entered by the user. The user has entered number 5. The statement
           
            fact=factorial(n1);

makes a call to the function. The variable n1 is now argument to the function factorial. The argument is mapped to the parameters in the parameter list of the function. The function header is
           
            int factorial(int n)

The body of the function contains two return statements. If the value entered by the user is less than and equal to 1 then value 1 is returned else computed factorial is returned. The type of the expression returned is integer.

Parameter passing mechanism

There are two parameter passing mechanisms for passing arguments to functions such as pass by value and pass by reference.

Pass by value

In pass be value mechanism copies of the arguments are created and which are stored in the temporary locations of the memory. The parameters are mapped to the copies of the arguments created. The changes made to the parameter do not affect the arguments. Pass by value mechanism provides security to the calling program. Here is a program which illustrates the working of pass by value mechanism.

#include<iostream>
using namespace std;
int add(int n);

int main()
{
            int number,result;
            number=5;
            cout << " The initial value of number : " << number << endl;
            result=add(number);
            cout << " The final value of number : " << number << endl;
            cout << " The result is : " << result << endl;
            return(0);
}

int add(int number)
{
            number=number+100;
            return(number);
}

The result of the program is:-


The value of the variable number before calling the function is 5. The function call is made and function adds 100 to the parameter number. When the function is returned the result contains the added value. The final value of the number remains same as 5. This shows that operation on parameter does not produce effect on arguments.

Pass by reference

Pass by reference is the second way of passing parameters to the function. The address of the argument is copied into the parameter. The changes made to the parameter affect the arguments.  The address of the argument is passed to the function and function modifies the values of the arguments in the calling function. Here is a program which illustrates the working of pass by reference mechanism.

#include<iostream>
using namespace std;
int add(int &number);

int main ()
{
            int number;
            int result;
            number=5;
            cout << "The value of the variable number before calling the function : " << number << endl;
            result=add(&number);
            cout << "The value of the variable number after the function is returned : " << number << endl;
            cout << "The value of result : " << result << endl;
            return(0);
}

int add(int &p)
{
            *p=*p+100;
            return(*p);
}

The result of the program is:-

           

The address of the variable is passed to the function. The variable p points to the memory address of the variable number. The value is incremented by 100. It changes the actual contents of the variable number. The value of variable number before calling the function is 100 and after the function is returned the value of variable number is changed to 105.

           
           
After an introduction of functions, let us move on to discuss structures.

Compound Data Types: Pointer in C++

                                                Pointers

Before reading this tutorial, you should have knowledge of arrays.

A pointer is a variable that is used to store a memory address. The address is the location of the variable in the memory. Pointers help in allocating memory dynamically. Pointers improve execution time and saves space.  Pointer points to a particular data type. The general form of declaring pointer is:-

            type *variable_name;

type is the base type of the pointer and variable_name is the name of the variable of the pointer. For example,

            int *x;

x is the variable name and it is the pointer of type integer.  

Pointer Operators

There are two important pointer operators such as ‘*’ and ‘&’. The ‘&’ is a unary operator. The unary operator returns the address of the memory where a variable is located.  For example,

            int x*;
            int c;
            x=&c;

variable x is the pointer of the type integer and it points to location of the variable c. When the statement
                       
                        x=&c;

is executed, ‘&’ operator returns the memory address of the variable c and as a result x will point to the memory location of variable c.

The ‘*’ operator is called the indirection operator. It returns the contents of the memory location pointed to.  The indirection operator is also called deference operator. For example,

            int x*;
            int c=100;
            int p;
x=&c;
            p=*x;

variable x is the pointer of integer type. It points to the address of the location of the variable c. The pointer x will contain the contents of the memory location of variable c. It will contain value 100. When statement
                       
p=*x;

is executed, ‘*’ operator returns the content of the pointer x and variable p will contain value 100 as the pointer x contain value 100 at its memory location.  Here is a program which illustrates the working of pointers.

#include<iostream>
using namespace std;

int main ()
{
            int *x;
            int c=200;
            int p;
            x=&c;
            p=*x;
            cout << " The address of the memory location of x : " << x << endl;
            cout << " The contents of the pointer x : " << *x << endl;
            cout << " The contents of the variable p : " << p << endl;
            return(0);
}

The result of the program is:-


In the program variable x is the pointer of integer type. The statement

            x=&c;

points variable x to the memory location of variable c. The statement

            p=*x;

makes the contents of the variable p same as the contents of the variable c as x is pointing to the memory location of c.  The statement

          cout << " The address of the memory location of x : " << x << endl;

prints the memory address of variable x which it is pointing to. It prints the hexadecimal address 0012FF78. This address will be different when the program is run on different computers. The statement

             cout << " The contents of the pointer x : " << *x << endl;

prints the contents of memory location of the variable x which it is pointing to. The contents are same as the variable c which has value 200.  The statement

            cout << " The contents of the variable p : " << p << endl;

has the same output 200 as the statement above. The contents of variable p is same as the contents of the pointer x.

Pointer Arithmetic

There are only two arithmetic operations that can be performed on pointers such as addition and subtraction. The integer value can be added or subtracted from the pointer. The result of addition and subtraction is an address. The difference of the two memory addresses results an integer and not the memory address. When a pointer is incremented it points to the memory location of the next element of its base type and when it is decremented it points to the memory location of the previous element of the same base type. For example,

            int *x;
            int *p;
            p=x++;

here x and p are pointers of integer type. Pointer x is incremented by 1. Now variable p points to the memory location next to the memory location of the pointer x. Suppose memory address of x is 2000 and as a result p will contain memory address 2004 because integer type takes four bytes so the memory address is incremented by 4. Incrementing the pointer results in incrementing the memory address by the number of bytes occupied by the base type. For example,

      double *x;
      double *p;
      p=x++;

variables x and p are pointers of double type. Pointer x is incremented by 1. Now if the memory address of x was 2000 and after incrementing p will contain memory address 2008 as double takes 8 bytes. Decrementing the pointer results in decrementing the memory address by the number of bytes occupied by the base type. You cannot add two pointers. No multiplication and division can be performed on pointers. Here is a program which illustrates the working of pointer arithmetic.

#include<iostream>
using namespace std;

int main ()
{
            int *x;
            int *p,*q;
            int c=100,a;
            x=&c;
            p=x+2;
            q=x-2;
            a=p-q;
            cout << "The address of x : " << x << endl;
            cout << "The address of p after incrementing x by 2 : " << p << endl;
            cout << "The address of q after derementing  x by 2 : " << q << endl;
            cout << " The no of elements between p and q :" << a << endl;
            return(0);
}

The result of the program is:-


In the program x, p and q are pointers of integer type. The statement

            p=x+2;

makes p to point to the memory address which is next two memory locations apart from the location of x.  The statement

          q=x-2;

makes q to point to memory address which is previous two memory locations apart from the location of x. The statement

            a=p-q;

computes the no of memory locations between p and q will come out to be 4. The statement
           
cout << "The address of x : " << x << endl;

prints the address of the memory location of x which is 0012FF70. The statement

            cout << "The address of p after incrementing x by 2 : " << p << endl;

prints the memory address of p which comes out to be 0012FF78. Each memory location occupies 4 bytes. Therefore after incrementing by 2, memory address is incremented by 8. The statement

            cout << "The address of q after decrementing  x by 2 : " << q << endl;

prints the memory address of q which is 0012FF68. After decrementing, the memory address is decremented by 8. The statement

            cout << " The no of elements between p and q :" << a << endl;

prints the no of memory locations between p and q which comes out to be 4 as p points to next two memory locations of x and q points to the previous two memory locations of x.

Pointers and Arrays

The pointers and arrays have a very close relationship. The pointer can be set to the address of the first element of the array. For example,

            int age[];
            int *p;
            p=&age;
p will point to the address of the first element of the array. For example

            (p+4)

will point to the fifth element of the array.  Pointers are helpful where size of the array is unknown. Declaring the array with a size of large value wastes lot of space. Pointers improve the execution time. Here is a program which illustrates the working of arrays and pointers.

#include<iostream>
using namespace std;

int main()
{
            int age[5];
            int *p;
            int sum=0,i;
            char yes='y';
            p=age;
            for(i=0;i<5;i++)
            {
                        cout << "Enter the age of a student" << endl;
                        cin >> *p;
                        sum=sum+*p;
                        p++;
            }
            p=age;
            cout << "The sum of the ages" << sum << endl;\
            cout << "The age of the last student is : " << *(p + 4) << endl;
            return(0);
}

The result of the program is:-


The array age is of integer type. The pointer p points to the first element of the array.
           
            p=age;

The user is allowed to enter the age of the student. The statement

            cin >> *p;

stores the age of the person in contents of the array.  The pointer is incremented by one memory location so that next time age is stored in new memory location.

            p++;

sum of the ages is calculated. The pointer is again referred to the address of the first element of the array. The age of the last student cab be accessed using *(p+4) which contains the value of the 5th element of the array.


After an introduction of arrays, let us move on to discuss functions.

Compound Data Types: Arrays in C++

  Arrays

Before reading this tutorial, you should have knowledge of loop statements.

An array is a collection of several data items of the same data type. It consists of several contiguous memory locations storing data. It removes the cumbersome task of defining separate variables for each data item. A single variable can be used to store one or more data items. For example, if you want to store ages of 10 students of a class, you can easily declare an array of integer type of size 10 instead of declaring 10 variables of integer type each storing age of a student. The general form of the single dimension array is:-

type variable_name[size];

The type is the base type of the array and which is the type of each of the element of the array. The size is the no of the elements in the array. The variable_name is the name of the identifier holding the array. For example,

int age [10];

The age is an array of type integer whose size is 10. It can hold 10 data values. The specific element in the array  can be accessed using an index. An index is the offset from the first element of the array. For example, first element has an index of 0 while the third element has an index of 2. The integer age has elements from age[0] to age[9]. Here is a program which illustrates the working of arrays.
#include<iostream>
using namespacestd


#include<iostream>
using namespace std;
int main ()
{
           int age[10];
           int i,sum=0, avg=0;
           int max=0,min=100;
            for(i=0;i<10;i++)
            {
                       cout << "Enter the age of the student  " << i+1 <<endl;
                       cin >> age[i];
             }
            for(i=0;i<10;i++)
            {
                        sum=sum+age[i];
                        if(age[i]>max)
                        {
                                    max=age[i];
                        }
                        if(age[i]<min)
                        {
                                    min=age[i];
                        }
            }
            avg=sum/10;
            cout << "Average age of the students of the class : " << avg << endl;
            cout << "Maximum age of the student of the class : " << max << endl;
            cout << "Minimum age of the student of the class : " << min << endl;
            return(0);
}

The result of the program is:-


In the program the array is declared by the statement

            int age[10];

age is the identifier of the array which is of type integer and whose size is 10. In the for loop user is asked to enter the age of the student, the age is stored in the element of the array by the statement
                       
            cin >> age[i];

here i is the index of the array. The index starts from 0.  In the next for loop, average age, minimum age and maximum age of the students is calculated. Each element is accessed by index i. The sum of the elements of the array is calculated by the statement
            sum=sum+age[i];

age[i] is the (i+1)th element of the array. The maximum age is calculated by the if statement
                        if(max>age[i])
                        {
                                    max=age[i];
                        }
The minimum age is calculated by the another if statement
                       
                        if(min<age[i])
                        {
                                    min=age[i];      
                        }
The average is calculated by the statement

                        avg=sum/10;

The total no bytes used to store an array is equal to
                        Total bytes=size of(base type)×size of array.

Initializing Arrays

The arrays can be initialized by giving the initial values in a list and enclosed in curly brackets, which is placed after the equal sign which is put after the declaration of the array. For example,
           
            int age[5]={12,13,10,24,15};

elements of the array have values 12, 13, 10, 24, 15. The elements age[0] has value 12 and age[4] will have 15.  If the elements of the array are not initialized then they take some garbage value before they are assigned to some specified value. There is also another way of initializing all the elements of the array to be zero. For example,

            int age[5]={0};

will initialize all the elements of the array age to be zero. If you want some of the elements to be initialized with specific value and rest of the values to be zero then here is an example.
                       
            int age[5]={12,13};

The elements age[0] and age[1] will be initialized to 12 and 13 respectively and rest of the elements will be initialized to zero.


Null Terminated Strings
 
The most common use of one dimensional array is for character strings.  The null terminated string is a character array with a null character at the end. The characters form the string with a null character indicating the termination of the string. A null terminated string can be declared as

            char name[10];

it will hold 10 characters with a null at the end. The size of the array can be more than the length of the array. The array can be initialized as

            char name[10]={'j','e','s','u','s'};

The first 5 elements are initialized and rest elements are null characters. Here is a program which calculates the length of the string.

#include<iostream>
using namespace std;

int main()
{
            char name[15];
            int i=0;
            cout << " Enter your name " << endl;
            cin >> name;
            while(name[i]!='\0')
            {
                        i++;
            }
            cout << "Lenght of the name is : " << i << endl;
            return(0);
}

The result of the program is


The character array is declared by the statement

            char name[15];

The length of the name can be at most 15.  The arrays is assigned by taking the input from the user by the statements
                       
            cout << " Enter your name " << endl;
            cin >> name

Variable name is assigned the string entered by the user.  Each element of the array is referenced and checked whether it is null or not by the statement
                       
while(name[i]!='\0')

Until a null character is not encountered variable i is incremented by the statement
           
i++;

When a null character is encountered while loop is terminated and length is printed by the statement

            cout << "Length of the name is : " << i << endl;

 
Multidimensional Arrays
 
The multidimensional arrays are arrays of arrays. The general form of a multidimensional array is: -
            type variable_name[Size1][Size2]..[Size n];

The two dimensional array can be declared as

            int age[2][5];

this array has two rows and 5 columns. The three dimensional array can be declared as

            int age[2][3][5];

When an element of the array of n dimensional is referenced it uses n index values. For example first element of a two dimensional array declared above is referred as age[0][0] as the index starts from zero and last element is referred as age[1][4]. Here is a program which calculates the average of the elements of the row of the two dimensional array.

#include<iostream>
using namespace std;

int main ()
{
            int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};
            int i,j;
            int sum=0,avg=0;
            for(i=0;i<2;i++)
            {
                        for(j=0;j<5;j++)
                        {
                                    sum=sum+age[i][j];
                        }
                        avg=sum/5;
                        cout << "Average of the elements of the row " << i+1  << " is " << avg << endl;
                        sum=0;
            }
            return(0);
}

The result of the program is: -


The program initializes and declares the two dimensional array by the statement

            int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};

Elements of the first row and second row are initialized as {12,13,14,15,15} and
{ 12,16,17,13,12}  respectively. The elements are accessed using the statement as

            sum=sum+age[i][j];

age[i][j] refers to the element of row i and column j. This statement calculates the sum of the elements of the row.  After the sum of the elements of a row is calculated then average is calculated by the statement.
           
avg=sum/5;

sum is again initialized to zero. Then again the same process repeats for the second row.

After an introduction of arrays, let us move on to discuss pointers.