C++

Depending on the object features supported, the languages are classified into two categories:

  1. Object-Based Programming Languages –> Encapsulation + Object Identity.
  2. Object-Oriented Programming Languages –> Object-Based features + Inheritence + Polymorphism.

 

OBJECT-ORIENTED PROGAMMING LANGUAGE

A language which satisfies following four important principles is said to be pure object oriented programming languages:

  1. Encapsulation: It is a mechanism that associates  the code and the data it manipulates into a single unit.

It means in Object-Oriented approach, data and function are treated as a single entity not saperate entity. By single entity it keeps them safe from external interface. It provides security. We can protect the code of a program by enclosing the code under a wrapper known as class.

NOTE: Encapsulation is all about hiding of the code.

 

  1. Abstraction: Creating new data types using encapsulated items, that are well suited to an application to be programmed is known as data abstraction.

 

  1. Inheritence: This concept involves the creation of new classes (derived class) from the existing ones (base classes). According to this the parent property can be consumed by children i.e. Reusing. In an object-oriented programming language we can reuse the member defined in a class from another class by establishing Parent-Child relationship between classes.

 

  1. Polymorphism: Behaving in different ways depending upon the input recieved is known as polymorphism. This can be implemented under an object-oriented language using the approaches like overloading, overriding and  hiding.

 

Since, data and its associated set of functions are enclosed under a class. Class is a user defined data type. A data type never used to occupy spaces in the memory. It requires a copy of data type to occupy the spaces in the memory. For the complex data types such as class, structure   etc, the copy of these are known as object. By the help of object only we can invoke the methods inside a class. So, this approach is known as Object-Oriented approach.

C++

Bjarne Stroustrup developed C++ at AT&T Bell laboratories in the year 1980.

//My First Program

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

cout<<“Hello World”;

getch();

}

Explanation:

1: //My First Program                         –> Comment

 

2: #include<iostream.h>                    –> Pre-processor Directive

 

3: #include<conio.h>                        –> Pre-processor Directive

 

4: void main()                                     –> Function Declatator

 

5: {                                                     –> Function Begin

 

6: clrscr();

7: cout<<“Hello World”;                      –> Function Body
8: getch();

 

 

9: }                                                    –>Function End

 

 

 

Comment Line –>  The statement which starts with symbol // is the comment line. The compiler ignores the comment line. Hence it does not slow down the speed of program execution and also it does not increase the size of executable program. It is a good practise to use the comments in the program where ever required to make our program descriptive.

 

Pre-processor Directive –> It contains various instructions and pre-                                                                  defined constants or functions that will be used in the programs such as cout, cin, getch() etc. It contains dclarations that are needed by  pre-defined functions. cout and cin function comes under <iostream.h> whereas getch() functio comes under <conio.h>.

 

Function Declarator –> Every C++ program must have a main() function. It is the point from where the execution begins. The name main is a special word, it is not a reserved word. So it cannot be invoked any where by the programmer. Every    function must have a pair of parenthesis. It may or may not contain parameter. Every function must be preceedee by a <type>. It should return a value. In case if we not want to  return a value, we should use void.

 

Function Begin –> The body of a function must be enclosed in two flower braces({ }). The opening braces ( { )indicates the begining of the function.

 

The function clrscr() is used to clear the console ( the screen where output displays) from previous outputs. It is good programming practise to use clrscr() function.

The statement

cout<<“Hello World”;

prints the message Hello World on the terminal. The cout (Console output) is the output statement used to print the messages.

 

The function getch() is used to return the statement on the console.

 

Function End –> The end of a function body in a C/C++ program is marked by the closing flower bracket( } ). When the    compiler encounters this bracket, it is replaced by the statement

return;

which transfers control to a caller. In this program, the last line actually marks the end of program and control is transfer to the operating system on termination of the program.

 

C++ new features for handling I/O operations are called streams. Streams are abstractions that refer to data flow. Streams in C++ are classified into :-

  1. Output stream
  2. Input stream.

 

  1. Output stream :- The output stream allows to perform write operations on output

devices.

The complete syntax for standard output streams operations is:

cout<<variable 1<<variable 2<<…………….<<variable n;

The word cout is followed by the symbol <<, called the insertion or put-to-operator.

More than one item can be displayed using a single cout output stream object. Such

output operations in C++ are called as cascaded output operations.

e.g.  cout<<“Age=”<<age;

The cout object will display all the items from left to right.

 

NOTE :-  The item endl serves the same purpose as “\n”(linefeed and carriage return) and is known as manipulator.

  1. Input stream  :-  The input streams allow to perform read operations with input devices.

The complete syntax for standard input streams operations is:

cin>>variable 1>>variable 2>>…………….>>variable n;

The word cin is followed by the symbol >>, called the extraction operator.

More than one item can be displayed using a single cin input stream object. Such output   operations in C++ are called as cascaded input operations.

e.g.  cin>>name>>age;

The cin object will display all the items from left to right.

 

The following are two important points to be noted about the stream operations:

a)      Streams do not require explicit data type specification in I/O statement.

b)      Streams do not require explicit address operator prior to the variable in the input statement.

 

C++ supports a mechanism to access a global variable from a function in which a local variable is defined with the same name as a global variable. It is achieved using the scope resolution operator(::).

The syntax for the scope resolution operator is:

:: GlobalVariableName

 

The variable initialized before the main function is called the global variable. The global variable to be accessed must be preceded by scope resolution operator. it directs the compiler to access the global variable instead of local variable.

The scope resolution operator permits a program to reference an identifier in the global scope that has been hidden by another identifier with the same in the local scope.

#include<iostream.h>

#include<conio.h>

int num=20;

void main()

{

int num=10;

clrscr();

cout<<“Local=”<<num;      //Local variable

cout<<“Global=”<<::num;   //Global variable

cout<<“\nGlobal+Local=”<<::num+num;   //both local & global use

getch();

}

 

Output:

 Local=10

 Global=20

 Global+Local=30

 

In case we don’t initialized a local variable , then cout function will print the value of global variable even if  we don’t preceded the variable name by scope resolution operator.

e.g.

#include<iostream.h>

#include<conio.h>

int num=10;

void main()

{

clrscr();

cout<<num<<endl;      //Global variable

int num=20;                     //Local Variable

{

int num=30;                     //Local Variable inside a block

cout<<num<<endl;     //Print block value

cout<<::num<<endl;   //Print Global Value

}

cout<<num<<endl;      //print Local Value 

cout<<::num;   //Global variable

getch();

}

 

Output:

10

30

10

20

10

 

 

But if we only declare the local variable not initialize and then perform output function , then it will print a garbage value.

e.g.

#include<iostream.h>

#include<conio.h>

int num=10;

void main()

{

clrscr();

int num;                              //Declaring a local variable

cout<<num<<endl;      //Garbage variable

{

int num=30;                     //Local Variable inside a block

cout<<num<<endl;     //Print block value

cout<<::num<<endl;   //Print Global Value

}

cout<<num<<endl;      //Garbage value 

cout<<::num;   //Global variable

getch();

}

 

Output:

Garbage value

30

10

Garbage value

10

 

 

 

 

 

 

 

 

REFERENCE VARIABLE

In addition to value variable and pointer variable, there is one more type of variable is reference variable.

Value variables used to hold numeric values.

Pointer values are used to hold the addresses of some other value variables.

Reference variables behave similar to both, a value variable and a pointer variable. In other words, a reference variable acts as an alias(alternate name) for the other value variable. It is used similar to that of the value variable but acts as a pointer variable.

 

Syntax to define reference variable:

DataType & ReferenceVariable = ValueVariable

e.g         int &m=n;         or          int & m = n;

Reference variable must be initialised to some variable only at the point of its declaration. Initialization of reference variable after its declaration causes compilation error.

int &m= 100;  //Invalid

This statement will cause compilation error because constants can not be pointed by a reference variable.

e.g

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int  a=1,b=2,c=3;

int &z=a;      //Variable z becomes alias of a.

cout<<“z=”<<a<<endl;

z=b;     //Value of b is assigned to a because Variable z becomes alias of a.

cout<<“z=”<<a<<endl;

z=c;      //Value of c is assigned to a because Variable z becomes alias of a.

cout<<“z=”<<a<<endl;

getch();

}  

 

 

Output:

z=1

z=2

z=3

In the above program the memory address of a and z will be same because The reference variables are to bound to its memory locations at the compile time only.

Program to demonstrate the reference variable

#include<iostream.h>

#include<conio.h>

       void main()

              {

                     clrscr();

                     int x=10;

                     int &x_ref=x;

                     cout<<“Value of x is”<<” ” <<x<<endl;

                     cout<<“Value of x_refis”<<” “<<x_ref;

                     cout<<endl<<“Address of x is”<<” “<<&x;

                     cout<<endl<<“Address of x_ref”<<” “<<&x_ref;

                     x_ref++;

                     cout<<endl;

                     cout<<“Value of x is”<<” ” <<x<<endl;

                     cout<<“Value of x_refis”<<” “<<x_ref;

                     int y=50;

                     x_ref=y;

                     cout<<endl;

                     cout<<“Value of x is”<<” ” <<x<<endl;

                     cout<<“Value of x_refis”<<” “<<x_ref;

                     int &x_ref1=x;

                     cout<<endl;

                     cout<<“Value of x_ref1 is”<<” ” <<x_ref1<<endl;

                     cout<<“Address of x_ref1 is”<<” “<<&x_ref;

                     getch();

              }

 

 

 

 

FUNCTION

Introduction, Basic and Concepts

 

Parameter passing is a mechanism for communication of data and information between the calling function (caller) and the called function (callee). It can be achieved either by passing the value or address of the variable. C++ supports the following three types of parameter passing schemes:

  • Pass by value
  • Pass by address
  • Pass by reference ( only in C++).

 

PASS BY REFERENCE

Passing parameter by reference has the functionality of pass – by – pointer and the syntax of call – by – value. In this case, an alias (reference) of the actual parameter is passed. Any modification made through the formal pointer parameter is also reflected in the actual parameter. Therefore, the function body and the call to it is identical to that of call – by – value, but has the effect of call – by – pointer.

To pass an argument by reference, the function call is similar to that of call – by – value. In the function declarator, those parameters, which are to be received by reference must be preceded by & operator. The reference type formal parameter are accessed in the same way as normal value parameters. Any modification to them will also be reflected to the actual parameter.

 

 

 

 

 

 

 

 

 

 

 

 

 

//Program to illustrate pass by reference

#include<iostream.h>

#include<conio.h>

       void swap(int &x, int &y)

              {

                     int t;

                     t=x;

                     x=y;

                     y=t;

              }

 

       void main()

              {

                     clrscr();

                     int a,b;

                     cout<<“Enter the value of a:”;

                     cin>>a;

                     cout<<endl<<“Enter the value of b:”;

                     cin>>b;

                     swap(a,b);

                     cout<<endl<<“On swapping”;

                     cout<<endl<<“Value of a:”<<a;

                     cout<<endl<<“Value of b:”<<b;

                     getch();

              }

In main(), the statement

            swap ( a , b ) ;

is translated into

            swap ( &a , &b ) ;

internally during compilation.

The function declarator

void swap ( int &a , int &b ) ;

indicates that the formal parameters are of reference type and hence, they must be bound to the memory location of actual parameter. Thus, any access made to the reference formal parameters in the swap() function refers to the actual parameters.

The following statements in the body of the swap() function:

                t=x;

x=y;

       y=t;

have the following interpretation internally:

 

 

t = *x;      

*x = *y;     

*y = t;

This is because, the formal parameters are of reference type and therefore the compiler treats them similar to pointers but does not allow the modification of the pointer value. Changes made to the formal parameters x and y reflect on the actual parameters a and b.

Return by Reference

A function that returns a reference variable is actually an alias for the referred variable.

//Program to illustrate concept of return by reference

#include<iostream.h>

#include<conio.h>

       int &max(int &x, int &y)

              {

                     if(x>y)

                           return x;

                     else

                           return y;

              }

       void main()

              {

                     clrscr();

                     int a,b;

                     cout<<“Enter the value of a:”;

                     cin>>a;

                     cout<<“Enter the value of b:”;

                     cin>>b;

                     max(a,b)=200;

                     cout<<“a=”<<a;

                     cout<<endl<<“b=”<<b;

                     getch();

              }

 

Explanation: In main(), the statement, max(a,b)=200; invokes the function max. It returns the reference to the variable holding the maximum value and assigns the value 200 to it. Since, the return type of the max() is int &, it implies that the call to max() can appear to the left-hand side of an assignment statement. Therefore, the above statement is valid and assigns 200 to a if it is larger, otherwise, it is assigned to b.

DEFAULT ARGUMENT

A default argument is a value that is used automatically as the function argument when we omit the actual argument from a function call.

 

 

 

How do we establish a default value for a function parameter?

To establish a default value, we must use the function prototype. The compiler looks at function prototype to find out the number and type of the argument list the function uses. The function prototype also has to alert the program to the possibility of default arguments. The method is to assign the default value to the argument in the prototype.

To set up 5 as the default argument for the function void func(int n), we have to modify the function prototype as:

void func(int n=5);

When we use a function with argument list, we must add defaults from right to left.

void func(int m, int n, int j);          // valid

void func(int m, int n, int j=5);        // valid

void func(int m, int n=2, int j=5);      // valid

void func(int m, int n=4, int j);        // invalid

void func(int m=1, int n=2, int j=3);    // valid

void func(int m=1, int n, int j);        // invalid

If void func(int x=1, int y=2, int z=3); is the function prototype, then

func(10,3,5);  is valid

func(10,3);  is valid and is same as func(10,3,3);

func(10);  is valid and is same as func(10,2,3);

func();  is valid and is same as func(1,2,3);

func(1,2,3);  is valid

Program to illustrate the above concept

#include<iostream.h>

#include<conio.h>

       void printline(char ch=’-‘, int n=20);

       void main()

              {

                     clrscr();

                     printline();

                     printline(‘!’);

                     printline(‘*’,10);

                     getch();

              }

       void printline(char ch, int num)

              {

                     for(int i=0;i<=num;i++)

                                  cout<<ch;

                     cout<<endl;

              }

 

 

INLINE FUNCTION

Inline function is a C++ enhancement designed to speed up program execution. The primary distinction between inline functions and normal functions is not in the way we code them, but in the way the compiler incorporates them into a program.

Normal function call involves many different operations. When a function call is executed the following activities takes place.

  1. The CPU stores the memory address of the instruction following the function call.
  2. The parameters of the function calls are copied into the temporary variables created onto a stack.
  3. The CPU control is transferred to the starting address of the function segment. The CPU then executes the function code . Probably it may return some value to the calling function. This value is then copied into memory location/CPU registers.
  4. The calling function retrieves the returned value from the appropriate register or memory locations and uses it in the rest of the program.

Normal function calls thus involve an overhead in terms of CPU time. This is an overhead in terms of storage space also.

C++ provides an alternative to normal function calls in the form of inline functions.

Inline functions are those whose function body is inserted in place of function call statement during the compilation process.

The concept of inline function is similar to macro functions in C.

To use inline functions in our program, we have to do two things:

i.            Preface the function prototype declaration with the keyword inline.

ii.            Place the function definition above all the function that call it.

 

 

 

 

 

 

Program to demonstrate inline function

#include<iostream.h>

#include<conio.h>

       inline double square(int n)

              {

                     return n*n;

              }

       void main()

              {

                     clrscr();

                     int s,num=5;

                     s=square(num);

                     cout<<s;

                     cout<<endl<<num;

                     getch();

              }

Explanation: In main(), the statement, square(num); invokes the inline function square. It will suitable be replaced by the instruction(s) of the body of the function square() by the compiler.

Limitations: The compiler does not allow large segments of code to be grouped as inline functions. The compiler doesn’t treat functions with loops as inline. Recursion is not allowed as inline functions.

MACRO AND INLINE FUNCTIONS

The #define directive in C++ enables you to define and use macros in our program.

Program to illustrate macro

#include<iostream.h>

#include<conio.h>

#define SQUARE(x) (x*x)

       void main()

              {

                     clrscr();

                     int b,num=5;

                     b=SQUARE(num+1);

                     cout<<b;

                     cout<<endl;

                     cout<<num;

                     getch();

              }  

 

 

The above program generates the following output:

11

5

Explanation: In the above program, we have used macro. Macro templates used to replace with their macro expansions. So in the above program num+1 i.e. 5+1, replaces at their places. The compiler will treat it as (5+1*5+1). Then the result will be 5+5+1=11.

Now, we will recompile the above program with the concept of inline function.

#include<iostream.h>

#include<conio.h>

       inline double square(int n)

              {

                     return n*n;

              }

       void main()

              {

                     clrscr();

                     int s,num=5;

                     s=square(num+1);

                     cout<<s;

                     cout<<endl<<num;

                     getch();

              }

The above program generates the following output:

36

5

Explanation: In the above program, we have used the concept of inline function. Inline function used to replace the code with the statements. So in the above program num+1 i.e. 5+1, replaces at their places. The compiler will treat it as ((5+1)*(5+1)). Then the result will be 6*6=36.

It seems that macro definitions and inline functions are same. However, they are different. Inline function do parameter passing, macros do text substitution.

 

 

 

FUNCTION OVERLOADING OR FUNCTION POLYMORPHISM

Function polymorphism or function overloading is a concept that allows multiple functions to share the same function name with different argument types.

Program to illustrate function overloading

#include<iostream.h>

#include<conio.h>

       void show(int &a, int &b)

              {

                     int t;

                     t=a;

                     a=b;

                     b=t;

              }

       void show(char &ch1, char &ch2)

              {

                     char t;

                     t=ch1;

                     ch1=ch2;

                     ch2=t;

              }

       void show(float &x, float &y)

              {

                     float t;

                     t=x;

                     x=y;

                     y=t;

              }

       void main()

              {

                     clrscr();

                     int a,b;

                     cout<<“Enter the value of a:”;

                     cin>>a;

                     cout<<“Enter the value of b:”;

                     cin>>b;

                     show(a,b);

                     cout<<“On swapping <a,b> “<<a<<” “<<b<<endl;

                     char ch1,ch2;

                     cout<<endl<<“Enter the value of ch1:”;

                     cin>>ch1;

                     cout<<“Enter the value of ch2:”;

                     cin>>ch2;

                     show(ch1,ch2);

                     cout<<“On swapping <ch1,ch2> “<<ch1<<” “<<ch2<<endl;

                     float x,y;

                     cout<<endl<<“Enter the value of x:”;

                     cin>>x;

                     cout<<“Enter the value of y:”;

                     cin>>y;

                     show(x,y);

                     cout<<“On swapping <x,y> “<<x<<” “<<y<<endl;

                     getch();

              }

 

 

FUNCTION TEMPLATES

C++ allows to create a single function possessing the capabilities of several functions, which differ only in their data types. Such a function is called function template or generic function. It permits writing one source declaration that can produce multiple functions differing only in the data types.

The syntax of function template is as:

template <class T1,class T2,……>

return_type function_name (arguments of type T1,T2,…….)

{

Statements;

}

Program to illustrate function template

#include<iostream.h>

#include<conio.h>

template <class T>

T max(T & a,T & b)

{

if(a>b)

return a;

else

return b;

}

void main()

{

char a,b,c;

cout<<“Enter the value of a:”;

cin>>a;

cout<<“Enter the value of b:”;

cin>>b;

cout<<“Enter the value of c:”;

cin>>c;

c=max(a,b);

cout<<“\nmax= “<<c;

int x,y,z;

cout<<“\nEnter the value of x:”;

cin>>x;

cout<<“Enter the value of y:”;

cin>>y;

z=max(x,y);

cout<<“\nMax= “<<z;

getch();

}

 

 

 

FUNCTION WITH VARIABLE NUMBER OF ARGUMENTS

In C++, we have given facility to pass variable number of arguments. The va_arg, va_end and va_start macros provide access to these arguments in the standard form. They are used for stepping through a list of arguments when the called function doesn’t know the number and types of the arguments being passed. The header file stdarg.h declares one type (va_list) and three macros (va_arg, va_end and va_start ).

The syntax of macros handling variable number of arguments are the following:

#include<stdarg.h>

       void va_start (va_list ap, lastfix);

       type va_arg (va_list ap, type);

       void va_end (va_list ap);

va_list: This array holds information needed by va_arg and va_end. When a called function takes a variable argument list, it declares a variable ap of type va_list.

va_start: This routine sets ap to point to the first of the variable arguments being passed to the function. va_start must be used before the first call to va_arg or va_end. The macro va_start takes two parameters: ap and lastfix. ap is a pointer to the variable argument list. lastfix is the name of the last fixed parameter passed to the caller.

va_arg: This routine expands to an expression that has the same type and value as the next argument being passed. The variable ap to va_arg should be the same ap that va_start initialized.

When va_arg is used first time, it returns the first argument in the list. every successive use va_arg, returns the next argument in the list. it does this by first dereferencing ap, and then incrementing ap to the point to the following item. Each time va_arg is invoked, it modifies ap to point to the next argument in the list.

va_end: This macro helps the called function to perform a normal return. va_end might modify ap in such a way that it can’t be used unless va_start is recalled. va_end should be called after va_arg has read all the arguments.

Return Value: va_start and va_end return no values; va_arg returns the current argument in the list.  

            Thesyntax of function receiving variable number of arguments is:

ReturnType Func(arg1,…);

Note that the last three dots indicates that the function is of type variable arguments.

Program to demonstrate the concept of variable number of arguments to a function

#include<iostream.h>

#include<stdarg.h>

#include<conio.h>

       int add(int argc,…)

              {

                     int num,result;

                     va_list args;

                     va_start(args,argc);

                     result=0;

                           for(int i=0;i<argc;i++)

                                  {

                                         num=va_arg(args,int);

                                         result+=num;

                                  }

                     va_end(args);

                     return result;

              }

       void main()

              {

                     clrscr();

                     int sum1,sum2,sum3;

                     sum1=add(3,1,2,3);

                     cout<<“sum1= “<<sum1<<endl;

                     sum2=add(1,10);

                     cout<<“sum2= “<<sum2<<endl;

                     sum3=add(0);

                     cout<<“sum3= “<<sum3<<endl;

                     getch();

              }

In the above program, in the function call add(3,1,2,3);, the first 3 indicates the number of arguments to be passed. In the same way, in the function call add(1,10);, the 1 indicates the number of arguments to be passed.

In the definition of add, in place of argc and args, any other variable can be entered. But only three dots are required, not more than three.

 

 

 

The function declarator

int add( int argc,…);

indicates that it takes one known argument and the remaining are unknown arguments. The three dots indicate that the function takes any number of arguments, to which a chain has to be built.

In add() function, the statement

va_list args;

creates a pointer variable named args.

The macro call statement

va_start(args,argc);

links variable arguments to the variable args. The variable args is the last known argument and those that follow variable arguments.

The statement

num=va_arg(args,int);

accesses the argument of type integer and assigns to the variable num. later, args is updated to point to the next argument.

The statement

va_end(args);

indicates the end of access to variable arguments using args.

COMPLETE SYNTAX OF MAIN

The function main()  takes three input parameters called command line arguments. These are passed from the point of program execution (usually operating system shell or command prompt).

Syntax of main()

       Return_type main([int argc, char *argv[], [char **envp]])

              {

                     Body of main function

              }

 

The return type of main function must be either int or void. It is normally used to indicate the status of the program termination.

 

argc: Argument count, holds the values of the number of arguments passed to the main function and its value is always positive.

argv: Argument vector, holds pointer to the arguments passed from the command line. The meaning of various elements of the argv vector is as follows:

argv[0]= pointer to the name of the executable program file (command).

argv[1]=  argv[argc-1] = pointer to argument strings.

envp: Environmental parameter, holds pointer to environment variables set in the operating system during the program execution. It includes path and environmental parameters. It is optional and not a ANSI specification.

Program of command line arguments

#include<iostream.h>

#include<conio.h>

       void main(int argc,char *argv[])

              {

                     clrscr();

                     int i;

                     cout<<“Argument Count= “<<argc;

                     cout<<“\nProgram Name= “<<argv[0];

                     cout<<“\nArguments Vectors Are:\n”;

                           for(i=0;i<argc;i++)

                                  cout<<argv[i]<<“\n”;

                     getch();

              }   

 

To execute this program, make .exe file (press F9) of this program and goto the DOS shell. To goto DOS shell click on File menu of your editor and click on DOS shell. Now, give the path of your executable file.

To get the path of executable file, click on Option menu on your editor and click on directories. Then the following window will appear

 

Whatever the path will be in Output Directory box, is the path of your .exe file.

Suppose we save this program by name main.cpp.

Then on the dos shell type

Then press Enter key. The following prompt will appear

 

 

 

 

 

 

 

 

 

 

 

Here 3 indicates the number of argument.

Program name is the path of executable file.

In argument vector these information are stored as argv[2].

argv[0] = pointer to the name of executable program file

argv[1] is the first argument and argv[2] is the second argument.

 

STRUCTURES AND ENCAPSULATIONS

Like C structures, C++ structures also provide a mechanism to group together data of different types  into a single unit. In addition to this, C++ allows to associate functions as part of a structure. Thus, C++ structures provide a true mechanism to handle data abstraction. Such structures have two types of members- data members and member functions. Functions defined within a structure can operate on any member of the structure.

int x
int y
void read()
void show()

Here, int x and int y are data members and void read() and void show() are member functions.

The functions enclosed within a structure can access data or other member functions directly. Similar to the data members, member functions can be accessed using the dot operator.

Program to demonstrate the concept of structures and encapsulation

#include<iostream.h>

#include<conio.h>

       struct math

              {

                     int num1,num2;

                     void add(math m1,math m2)

                           {

                                  num1=m1.num1+m2.num1;

                                  num2=m1.num2+m2.num2;

                           }

                     void display()

                           {

                                  cout<<“num1= “<<num1<<endl;

                                  cout<<“num2= “<<num2;

                           }

              };

       void main()

              {

                     clrscr();

                     math m1,m2,m3;

                     cout<<“Enter the value in num1:”;

                     cin>>m1.num1;

                     cout<<“Enter the value in num2:”;

                     cin>>m1.num2;

                     m2=m1;

                     m3.add(m1,m2);

                     m3.display();

                     getch();

              }

Structures and classes exhibit the same set of features except that structure members are public by default, whereas class members are private by default.

UNIONS

A union allows the overlay of more than one variable in the same memory area. Normally, each and every variable is stored in the separate memory location, as a result, each variable have its own memory addresses. The union provides a means by which the memory space can be shared. A union enable us to treat the same space in the memory as a number of different variables. That is, a union offers a way for a section of memory to be treated as a variable of one type on one occasion, and as a different variable of a different type on another occasion.

Declaring a Union

In terms of declaration syntax, the union is similar to a structure. The method used to declare a structure is adopted to declare a union. A union data type is same as structure, except that it allows us to define variables, which share storage space. Note that only change is the substitution of the keyword struct by the keyword union.

The compiler will allocate sufficient storage to accommodate the largest element in the union.

Syntax:

            union Union_name

              {

                     Datatype member1;

                     Datatype member2;

                     …………………………………………

                     Datatype membern;

              };      

Program to demonstrate union

#include<iostream.h>

#include<conio.h>

       union student

              {

                     char *name;

                     int stu_id;

                     float marks;

              };

       void main()

              {

                     student s;

                     clrscr();

                     s.name=”Ashu Akash Singh”;

                     cout<<“Name is “<<s.name<<endl;

                     s.stu_id=101;

                     cout<<“Id is “<<s.stu_id<<endl;

                     s.marks=67;

                     cout<<“Marks is “<<s.marks;

                     getch();

              }

 

DIFFERENCE BETWEEN STRUCTURE AND UNION

Structures and unions have the same syntax in terms of declaration and definition of their variables. However, they differ in the amount of storage space required for their storage and the scope of their members.

Memory Allocation

The amount of memory required to store a structure variable is the sum of the sizes of all the members. On the other hand, in case of unions, the amount of memory required is always equal to that required by its largest member.

Operations on Members

Only one member of the union can be accessed at one time. This is because, at any instant, only one of the union variable can be active. The general rule the determining the active member is: only that member which is updated can be read. At this point, the other variables will contain meaningless values.

 

 

Program to demonstrate the above fact

#include<iostream.h>

#include<conio.h>

       union emp

              {

                     char name[25];

                     int idno;

                     float salary;

              };

       void show(union emp e)

              {

                     cout<<endl;

                     cout<<“Employee details……”<<endl;

                     cout<<“Name is “<<e.name<<endl;

                     cout<<“Id no. is “<<e.idno<<endl;

                     cout<<“Salary is “<<e.salary;

              }

       void main()

              {

                     clrscr();

                     emp e;

                     strcpy(e.name,”Ashu”);

                     show(e);

                     e.idno=4;

                     show(e);

                     e.salary=25000;

                     show(e);

                     getch();

              }

 

 

 

 

 

 

 

 

 

 

 

 

 

CLASSES AND OBJECTS

The object oriented approach centers around modeling the real-world problems in terms of objects (data decomposition).

Object oriented programming constructs modeled out of data types called classes. Defining variables of a class data type is known as a class instantiation and such variables are called objects. Objects is an instance of a class. A class encloses both the data and functions that operate on the data, into a single unit. The variables and functions enclosed in a class are called data member and member functions respectively.

Placing data and functions together in a single unit is the center theme of object- oriented programming.

Classes are the basic language construct of C++ for creating the user defined data types. They are syntactically an extension of structure. The difference is that, all the members of structures are public by default whereas, the members of classes are private by default. Class follows the principle that the information about a module should be private to the module unless it is specifically declared public.

CLASS SPECIFICATION

C++ provides support for defining classes, which is a significant feature that makes C++ an object oriented language. Classes contain not only data but also functions. The functions are called member functions and define the set of operations that can be performed on the data members of a class. Thus, a class cam be described as a collection of data members along with member functions. This property of C++, which allows association of data functions into a single unit is called encapsulation.

Syntax of class specification:

              class classname

                     {

                           // body of a class

                     };

In the above syntax, class is a keyword and classname is the name of user-defined class.

The class specifies the type and scope of its members. The keyword class indicates that the name which follows (classname) is an abstract data type. The body of the class is enclosed within the curly braces followed by semicolon. The body of a class contains declaration of variables and functions, collectively known as members. The variables declared inside a class are known as data members, and functions are known as member functions. These members are usually grouped under two sections, private and public, which define the visibility of members.

The private members are accessible only to their own class’s members. On the other hand, public members are not only accessible to their own members, but also from outside the class. The members in the beginning of class without any access specifier are private by default. Hence, the first use of the keyword private in a class is optional.

Sample code to illustrate the specification of class

class student

         {

              int roll_no;

              char name[20];

                     public:

                     void read(int roll_no_in, char *name_in)

                           {

                                  roll_no=roll_no_in;

                                  strcpy(name,name_in);

                           }

                     void display()

                           {

                                  cout<<“Roll No.”<<roll_no<<endl;

                                  cout<<“Name= “<<name;

                           }

         };

 

The name of data and member functions of a class can be same as those in other classes; the members of different classes don’t conflict with each other. However, more than one class with the same class name in a program is an error, whether the declaration are identical or not. A class can have multiple member functions (but not data members) with the same name as long as they differ in terms of signature; this feature is known as method overloading.

Like structures, the data members of the class cannot be initialized during their declaration, but they can be initialized by its member functions.

 

class test

       {

              int x=4;  // error

              void read

                     {

                           x=0;  //valid

                     }

       };

 

CLASS OBJECTS

A class specification only declares the structure of objects and it must be instantiated in order to make use of the services provided by it. The process of creating objects (variables) of the class is called class instantiation.

Syntax:

            class classname objectname,…..;

 

Here, the keyword class is optional.

The definition of an object is similar to that of a variable of any primitive data type. Objects can also be created by placing their names immediately after the closing brace like in the creation of the structure variables. In C++, the convention of defining objects at the point of class specification is rarely followed.

ACCESSING CLASS MEMBERS

Once an object has been created, it can access its members by using the member access operator, dot(.).

Syntax for accessing members (data and functions)

a)      Syntax for accessing data member of a class

                  objectName . dataMember

 

b)     Syntax for accessing member function of a class

                 objectName . functionName ( Actual Arguments )

 

 

 

 

 

 

 

 

Program to demonstrate the way to access the member function of a class

#include<iostream.h>

#include<conio.h>

#include<string.h>

                          class student

                           {

                                  private:

                                  int roll;

                                  char *name;

                                         public:

                                         void read(int roll_no,char *name1)

                                                {

                                                       roll=roll_no;

                                                       strcpy(name,name1);

                                                }

                                         void display()

                                                {

                                                      cout<<“Roll Number: “<<roll;

                                                      cout<<“\nName: “<<name;

                                                }

                           };

                          void main()

                           {

                                  clrscr();

                                  student s;

                                  cout<<“Student Details……\n”;

                                  s.read(10,”Ashu”);

                                  s.display();

                                  cout<<endl<<endl;

                                  s.read(11,”Akash”);

                                  s.display();

                                  getch();

                           }

 

DEFINING MEMBER FUNCTIONS

The data members of a class must be declared within the body of the class, whereas the member function of the class can be defined in any one of the following ways:

  • Inside the class specification
  • Outside the class specification

Member function defined inside the class body

The syntax for specifying a member function declaration is similar to a normal function definition except that it is enclosed within the body of a class. All the member function defined within the body of the class are treated as inline by default except those members having looping statements such as for, while etc. and it also depends on the compiler.

 

 

Program to demonstrate the member function defined inside class

#include<iostream.h>

#include<conio.h>

          class date

              {

                     int day;

                     int month;

                     int year;

                           public:

                           void dob(int d,int m,int y)

                                  {

                                         day=d;

                                         month=m;

                                         year=y;

                                  }

                           void display()

                                  {

                                         cout<<“DOB:- “<<day<<“-“<<month<<“-“<<year<<endl;

                                  }

              };

          void main()

              {

                     clrscr();

                     date d1,d2;

                     d1.dob(15,5,1989);

                     d2.dob(10,9,1990);

                     d1.display();

                     d2.display();

                     getch();

              }

 

Member function outside the class body

Another method of defining a member function is to declare function prototype within the body of the class and then define it outside the body of the class. Since the function defined outside the body of the class specification has the same syntax as normal function, there should be a mechanism of binding the functions to the class to which they belong. This is done by scope resolution operator (::). It acts as an identity level to inform the compiler, the class to which the function belongs.

Syntax:

class className

       {

              ……………….

              returnType memberFunction (arguments);

              ……………….

       };

returnType className :: memberFunction (arguments)

       {

              //body of the function

       }

The label className :: informs the compiler that the function memberFunction is the member of the class className. The scope of the function is restricted to only the objects and other members of the class.

Program to demonstrate the member function defined outside class

#include<iostream.h>

#include<conio.h>

       class date

              {

                     int day;

                     int month;

                     int year;

                           public:

                           void dob(int d,int m,int y);

                           void display();

              };

       void date::dob(int d, int m, int y)

              {

                     day=d;

                     month=m;

                     year=y;

              }

       void date::display()

              {

                     cout<<“DOB:- “<<day<<“-“<<month<<“-“<<year<<endl;

              }

       void main()

              {

                     clrscr();

                     date d1,d2;

                     d1.dob(15,5,1989);

                     d2.dob(10,9,1990);

                     d1.display();

                     d2.display();

                     getch();

              }

 

In the above definitions, the label date:: informs the compiler that the functions dob and display are the members of the class date. It can access all the members of the class date and also global data items and functions.

Some of the special characteristics of the member function are the following:

a)      A program can have several classes and they can have member function with the same name. The ambiguity of the compiler in deciding which function belongs to which class can be resolved by the use of membership level (className::), the scope resolution operator.

b)      Private member of a class, can be accessed by all the members of that class, whereas non-member functions are not allowed to access.

c)      Member function of the same class can access all other members of their own class without the use of dot operator.

ACCESSING MEMBER FUNCTION WITHIN THE CLASS

A member function of a class is accessed by the objects of that class using the dot operator. A member function of a class can call any other member function of its own class irrespective of its privilege and this situation is called nesting of member function.

 

 

 

 

 

 

 

Program to demonstrate nesting of member function

#include<iostream.h>

#include<conio.h>

       class number

              {

                     int num1,num2;

                     public:

                           void read()

                                  {

                                         cout<<“Enter the value of num1:”;

                                         cin>>num1;

                                         cout<<“Enter the value of num2:”;

                                         cin>>num2;

                                  }

                           int max()

                                  {

                                         if(num1>num2)

                                                return num1;

                                         else

                                                return num2;

                                  }

                           void display()

                                  {

                                         cout<<“Maximum: “<<max();

                                  }

              };

       void main()

              {

                     clrscr();

                     number n;

                     n.read();

                     n.display();

                     getch();

              } 

 

DATA HIDING

The purpose of data encapsulation is to prevent accidental modification of information of a class. It is achieved by imposing a set of rules- the manner in which a class is to be manipulated and the data and functions of the class can be accessed. The following are the three kinds of users of a class:

  • A class member, which can access all the data members and functions of its class.
  • Generic users, which define the instance of a class.
  • Derived classes, which can access members based on privileges.

Each user has different access privileges to the object. A class differentiates between access privileges by partitioning its contents and associating each one of them with any one of the following keywords:

 

 

  • private
  • public
  • protected

These keywords are called access-control specifiers. All the members that follow a keyword belong to that type. If no keyword is specified, then the members are assumed to have private privilege.

PRIVATE MEMBERS

The private members of a class have strict control. Only the member functions of the same class can access these members. The private members of a class are inaccessible outside the class.

class Inaccessible

       {

              int x;

              void display()

                     {

                           cout<<”Data = “<<x;

                     }

       };

void main()

       {

              Inaccessible obj;

              obj.x=5;      //Error: Invalid access

              obj.display();       //Error: Invalid access

       }

 

PROTECTED MEMBERS

The access control of the protected members is similar to that of private members and has more significance in inheritance. The data member and member function declared as protected can be accessed in derived classes.

PUBLIC MEMBERS

The members of a class, which are to be visible (accessible) outside the class, should be declared in public section. All data member and member functions declared in the public section of the class can be accessed without any restriction from anywhere in the program.

PASSING OBJECTS AS ARGUMENTS

It is possible to have functions which accepts object of a class as arguments. Like any other data type, an object can be passed as an argument to a function by the following ways:

  • pass-by-value, a copy of entire object is passed to the function.
  • pass-by-reference, only the address of the object is passed implicitly to the function.
  • pass-by-pointer, the address of the object is passed explicitly to the function

Program to demonstrate Passing Objects By Value

#include<iostream.h>

#include<conio.h>

       class measurement

              {

                     float feet;

                     float inches;

                           public:

                                  void init(float f,float i)

                                         {

                                                feet=f;

                                                inches=i;

                                         }

                                  void read()

                                         {

                                                cout<<“Enter feet: “;

                                                cin>>feet;

                                                cout<<“Enter inches: “;

                                                cin>>inches;

                                         }

                                  void show()

                                         {

                                                cout<<feet<<“-“<<inches<<endl;

                                         }

                                  void add(measurement m1,measurement m2)

                                         {

                                                feet=m1.feet+m2.feet;

                                                inches=m1.inches+m2.inches;

                                                       if(inches>=12.0)

                                                              {

                                                              feet=feet+1.0;

                                                              inches=inches-12.0;

                                                              }

                                         }

                     };

       void main()

              {

                     clrscr();

                     measurement m1,m2,m3;

                     m1.init(10.0,5.5);

                     m2.read();

                     cout<<“d1= “;

                     m1.show();

                     cout<<“d2= “;

                     m2.show();

                     m3.add(m1,m2);

                     cout<<“m3= “;

                     m3.show();

                     getch();

              }

 

Passing Objects by Reference

SAMPLE

Given the account numbers and the balance of two accounts, this program transfers a specified sum from one of these accounts to the other and then, updates the balance in both the accounts.

 

 

 

 

 

 

 

 

 

 

 

#include<iostream.h>

#include<conio.h>

             class account

              {

                     int acc_no;

                     float balance;

                           public:

                           void read()

                                  {

                                         cout<<“Enter the account no: “;

                                         cin>>acc_no;

                                         cout<<“Enter the balance: “;

                                         cin>>balance;

                                  }

                           void read(int acc_in)

                                  {

                                         acc_no=acc_in;

                                         balance=0;

                                  }

                           void read(int acc_in,float bal)

                                  {

                                         acc_no=acc_in;

                                         balance=bal;

                                  }

                           void display()

                                  {

                                         cout<<“Account number: “<<acc_no<<endl;

                                         cout<<“Balance: “<<balance<<endl;

                                  }

                           void money_transfer(account &acc,float amt);

                     };

             void account::money_transfer(account &acc,float amt)

              {

                     balance=balance-amt;

                     acc.balance=acc.balance+amt;

              }

             void main()

              {

                     clrscr();

                     float trans_amt;

                     account acc1,acc2,acc3;

                     acc1.read();

                     acc2.read(101);

                     acc3.read(102,1500);

                     cout<<“Account Information: \n\n”;

                     acc1.display();

                     acc2.display();

                     acc3.display();

                     cout<<“How much money is to be transferred from Account3 to Account1?”;

                     cin>>trans_amt;

                     acc3.money_transfer(acc1,trans_amt);

                     cout<<“\nUpdated balance……….\n\n”;

                     acc1.display();

                     acc2.display();

                     acc3.display();

                     getch();

              }

 

Passing Objects By Pointer

The members of object passed by pointer are accessed by using -> operator, and those have similar effect as those pass by value. The above program requires the following change if parameters are to be passed by pointer.

  1. The prototype of the member function money_transfer() has to be changed to:

void money_transfer( account * acc,float amt);

  1. The definition of the member function money_transfer() has to be changed to:

void account::money_transfer(account *acc,float amt)

            {

                        balance=balance-amt;

                        acc->balance=acc->balance+amt;

            }

  1. The statement invoking the member function money_transfer() has to be changed:

acc3.money_transfer(&acc1,trans_amt);

 

RETURNING OBJECTS FROM FUNCTIONS

Similar to sending objects as parameters to functions, it is also possible to return objects from functions. The syntax used is similar to that of returning variables from functions.

 

 

 

 

 

 

 

 

 

 

 

 

 

Program to demonstrate returning objects from functions

#include<iostream.h>

#include<conio.h>

            class measurement

              {

                     int feet;

                     float inches;

                           public:

                                  void get_data();

                                  void set_data(int f,float i);

                                  void show_data();

                                  measurement add_data(measurement m);

              };

            void measurement::get_data()

              {

                     cout<<“Enter the feet: “;

                     cin>>feet;

                     cout<<“Enter the inches: “;

                     cin>>inches;

              }

            void measurement::set_data(int f,float i)

              {

                     feet=f;

                     inches=i;

              }

            void measurement::show_data()

              {

                     cout<<feet<<“-“<<inches<<endl;

              }

            measurement measurement::add_data(measurement m)

              {

                     measurement temp;

                     temp.feet=feet+m.feet;

                     temp.inches=inches+m.inches;

                           if(temp.inches>=12)

                                  {

                                         temp.feet++;

                                         temp.inches=temp.inches-12;

                                  }

                     return(temp);

              }

            void main()

              {

 

                     clrscr();

                     measurement m1,m2,m3;

                     m1.get_data();

                     m2.set_data(10,5.5);

                     m3=m1.add_data(m2);

                     cout<<“m1= “;

                     m1.show_data();

                     cout<<“m2= “;

                     m2.show_data();

                     cout<<“m3= “;

                     m3.show_data();

                     getch();

              }

 

 

FRIEND FUNCTIONS

The concept of encapsulation and data hiding dictate that non-member functions should not be allowed to access an object’s private and protected members. One of the convenient features of C++ is allowing non-member function to access even the private members of a class using friend functions or friend classes. It permits a function or all the functions of another class to access a different class’s private members.

The function declaration must be prefixed by the keyword friend whereas the function definition must not be prefixed by the keyword friend.

The function could be defined anywhere in the program similar to any normal C++ function. The functions that are declared with the keyword friend are called friend function. A function can be friend of multiple classes.

A friend function possesses the following special characteristics:

  • The scope of a friend function is not limited to the class in which it has been declared as friend.
  • A friend function can’t be called using the object of that class; it is not in the scope of the class. It can be invoked like a normal function without the use of any object.
  • Unlike class member functions, it cannot access the class members directly. However, it can use the object and the dot operator with each member name to access both the private and public members.
  • It can be either declared in the private part or public part of a class without affecting its meaning.

Concerning the friendship between classes, the following should be noted:

  • Friendship is not mutual by default. That is, if once B is the friend of A, this doesn’t give A the right to access the private members of the class B.
  • Friendship, when applied to program design, is an escape mechanism which creates exceptions to the rule of data hiding. Usage of friend class should, therefore, be limited to those cases where it is absolutely essential.

 

 

Program to demonstrate the friend function

#include<iostream.h>

#include<conio.h>

            class two;

            class one

              {

                     int num1;

                     public:

                           void get_data()

                                  {

                                         cout<<“Enter the value in num1: “;

                                         cin>>num1;

                                  }

                     friend int add_data(one a,two b);

              };

            class two

              {

                     int num2;

                     public:

                           void get_data()

                                  {

                                         cout<<“Enter the value in num2: “;

                                         cin>>num2;

                                  }

                     friend int add_data(one a,two b);

              };

            int add_data(one a,two b)

              {

                     return a.num1+b.num2;

              }

            void main()

              {

                     clrscr();

                     one a;

                     two b;

                     a.get_data();

                     b.get_data();

                     cout<<“Sum of num1 and num2 is: “<<add_data(a,b);

                     getch();

              }

 

The null body class declaration statement,

class two;

appears in the beginning of the program; a class cannot be referred until it has been declared before the class one. It informs the compiler that class two is defined later.

FRIEND CLASSES

Friend functions permit an exception to the rules of data encapsulation. The friend keyword allows a function, or all the functions of another class to manipulate the private members of the original class.

Program to demonstrate Friend class

#include<iostream.h>

#include<conio.h>

            class boy

              {

                     int income1;

                     int income2;

                           public:

                                  void set_data(int i1,int i2)

                                         {

                                                income1=i1;

                                                income2=i2;

                                         }

                     friend class girl;

              };

            class girl

              {

                     int income;

                           public:

                                  void set_data(int i)

                                         {

                                                income=i;

                                         }

                                  int add_income(boy b)

                                         {

                                                return b.income1+b.income2;

                                         }

                                  void show()

                                         {

                                                boy b;

                                                b.set_data(100,200);

                                                cout<<“\nGirl’s income: “<<income;

                                  cout<<“\nBoy’s income1 in show(): “<<b.income1;

                                  cout<<“\nBoy’s income2 in show(): “<<b.income2;

                           cout<<“\nBoy’s total income in show(): “<<add_income(b);

                                         }

              };

            void main()

              {

                     clrscr();

                     boy b;

                     girl g;

                     b.set_data(1000,500);

                     g.set_data(2000);

                     cout<<“Boy’s total income: “<<g.add_income(b);

                     g.show();

                     getch();

              }

 

In this program, forward declaration of class girl is optional; since this class is the friend of class boy.

Class Friend To A Specified Class Member

When only specific member function of one class should be friend function of another class, it must be specified explicitly using the scope resolution operator (: 🙂.

Program to demonstrate the above concept

#include<iostream.h>

#include<conio.h>

                       class boy;

                       class girl

                           {

                                  int income;

                                         public:

                                                void set_data(int i)

                                                       {

                                                              income=i;

                                                       }

                                                void show()

                                                       {

                                                cout<<“\nGirl’s income: “<<income;

                                                       }

                                                int add_data(boy b);

 

                           };

                       class boy

                           {

                                  int income1;

                                  int income2;

                                         public:

                                                void set_data(int i1,int i2)

                                                       {

                                                              income1=i1;

                                                              income2=i2;

                                                       }

                                  friend int girl::add_data(boy b);

                           };

                       int girl::add_data(boy b)

                           {

                                  return b.income1+b.income2;

                           }

                       void main()

                           {

                                  clrscr();

                                  boy b;

                                  girl g;

                                  b.set_data(1000,5000);

                                  g.set_data(2000);

                                  cout<<“Boy’s total income: “<<g.add_data(b);

                                  g.show();

                                  getch();

                           }

 

 

 

 

 

 

 

 

 

 

 

 

CONSTRUCTORS AND DESTRUCTORS

Suppose a program of purchased gift items to be stored in a bag.

#include<iostream.h>

#include<conio.h>

const int MAX_ITEMS=25;

              class Bag

              {

                     int contents[MAX_ITEMS];

                     int itemcount;

                           public:

                                  void set_empty()

                                         {

                                                itemcount=0;

                                         }

                                  void put(int item)

                                         {

                                                contents[itemcount++]=item;

                                         }

                                  void show();

              };

              void Bag::show()

              {

                     for(int i=0;i<itemcount;i++)

                           {

                                  cout<<contents[i]<<” “;

                           }

              }

              void main()

              {

                     clrscr();

                     int item;

                     Bag b;

                     b.set_empty();

                     while(1)

                           {

                                  cout<<“\nEnter the item number to be put: “;

                                  cin>>item;

                                         if(item==0)

                                                break;

                                  b.put(item);

                                  cout<<“Items in bag: “;

                                  b.show();

                            }

                     getch();

              }

 

In main(), the statement

Bag b;

creates the object bag without initializing the itemcount to 0 automatically. It is performed by call to a function set_empty() as

b.set_empty();

According to the philosophy of OOPs, when a new object is created it will be naturally empty. It is therefore, clear that OOPs must provide a support for initializing objects when they are created, and destroy them when they are no longer needed. Hence, a class in C++ contains two special member functions dealing with the internal workings of the class. These functions are the constructors and destructors. A constructors enables object to initialize itself during creation and the destructors destroys the object when it is no longer required, by releasing all the resources allocated to it. These operations are called object initialization and cleanup.

CONSTRUCTORS

A constructor is a special member function whose main operation is to allocate the required resources such as memory and initialize the objects of its class. A constructor is distinct from other member function of the class, and it has the same name as its class. It is executed automatically when a class is instantiated. It is generally used to initialize object member parameters and allocate the necessary resources to the object members. The constructor has no return value specification (not even void).

The C++ run-time system makes sure that the constructor of the class is the first member function to be executed automatically when an object of the class is created. In other words, the constructor is executes every time an object of that class is defined. It is also possible to define a class which has no constructor at all; in such a case, the run-time system calls a dummy constructor (i.e. , which performs no action) when its object is created. The constructor which does not take arguments explicitly is called default constructor.

 

 

 

 

 

 

 

 

 

 

 

Sample program to test constructor

#include<iostream.h>

#include<conio.h>

         class test

              {

                     public:

                           test();

              };

         test::test()

              {

                     cout<<“Constructor of the class is called”<<endl;

              }

         test t;            //global object

         void func()

              {

                     test t1;

                     cout<<“Its func() function”<<endl;

              }

         void main()

              {

                     test t2;

                     cout<<“Its main() function”<<endl;

                     func();

                     getch();

              }

 

A constructor has the following characteristics:

  • It has the same name as that of the class to which it belongs.
  • It is executed automatically whenever the class is instantiated.
  • It does nit have any return type.
  • It is normally used to initialize the data members of a class.
  • It is also used to allocate resources, to the dynamic data members of a class.

PARAMETERIZED CONSTRUCTORS

Constructors can be invoked with arguments, just as in the case of functions. Constructors with arguments are called parameterized constructors. Since C++ allows function overloading, a constructors with arguments can co-exist with another constructor without arguments.

 

 

 

 

 

 

Sample program to illustrate the above fact

#include<iostream.h>

#include<conio.h>

const int MAX_ITEMS=25;

       class Bag

              {

                     int contents[MAX_ITEMS];

                     int itemcount;

                           public:

                                  Bag()

                                         {

                                                itemcount=0;

                                         }

                                  Bag(int item)

                                         {

                                                contents[0]=item;

                                                itemcount=1;

                                         }

                                  void put(int item)

                                         {

                                                contents[itemcount++]=item;

                                         }

                                  void show();

              };

       void Bag::show()

              {

                     if(itemcount)

                           for(int i=0;i<itemcount;i++)

                                  {

                                         cout<<contents[i]<<” “;

                                  }

                     else

                           cout<<“Nil”<<endl;

              }

       void main()

              {

                     clrscr();

                     int item;

                     Bag bag1;

                     Bag bag2=3;

                     cout<<“Bag1 initially has: “;

                     bag1.show();

                     cout<<“Bag2 initially has: “;

                     bag2.show();

                     while(1)

                           {

                                  cout<<“\nEnter the item number to be put: “;

                                  cin>>item;

                                         if(item==0)

                                                break;

                                  bag2.put(item);

                                  cout<<“Items in bag: “;

                                  bag2.show();

                            }

                     getch();

              }

 

 

DESTRUCTORS

When an object is no longer needed it can be destroyed. A class can have another special member function called the destructor, which is invoked when an object is destroyed. For objects which are local non-static variables, the destructor is called when the function in which the object is defined is about to terminate. For static or global variables, the destructor is called before the program terminates.

Destructor is a member function having the character ~(tilde) followed by the name of its class. It is invoked automatically to reclaim all the resources allocated to the object when the object goes out of scope and is when no longer needed.

Similar to constructor, a destructor must be declared in the public section of a class so that it is accessible to all its users. Destructors have no any return type. A class can not have more than one destructor.

Program to demonstrate destructor

#include<iostream.h>

#include<conio.h>

         class test

              {

                     public:

                           test()

                                  {

                                         cout<<“Constructor is called\n”;

                                  }

                           ~test()

                                  {

                                         cout<<“Destructor is called”;

                                  }

              };

         int main()

              {

                     clrscr();

                     test t;

                     cout<<“Terminating main\n”;

                     return 0;

              }

 

 

 

An interesting aspect of constructor and destructor is that it keeps track of the number of objects created and how many of them are still alive.

Program to demonstrate the above fact

#include<iostream.h>

#include<conio.h>

int obj_created=0;

int obj_alive=0;

       class object

              {

                     public:

                           object()

                                  {

                                         ++obj_created;

                                         ++obj_alive;

                                  }

                           ~object()

                                  {

                                          –obj_alive;

                                  }

                           void show();

              };

       void object::show()

              {

                     cout<<“Number of objects created: “<<obj_created<<endl;

                     cout<<“Number of objects alive: “<<obj_alive<<endl;

              }

       int main()

              {

                     clrscr();

                     object o1;

                     o1.show();

                           {

                                  object o2,o3;

                                  o2.show();

                           }

                     o1.show();

                     object o2,o3;

                     o3.show();

                     return 0;

              }

 

The following rules needed to be considered while defining a destructor for a given class:

  • The destructor function has the same name as the class but prefixed by a tilde(~)

The tilde distinguishes it from constructor of the same class.

  • Unlike the constructor, the destructor does not take any arguments. This is because there is only one way to destroy an object.
  • The destructor has neither, nor a return value.
  • There can be only one destructor in each class.

 

CONSTRUCTOR OVERLOADING

A class can have multiple constructors. This is called constructor overloading. All the constructors have the same name as the corresponding class, and they differ only in terms of their signature.

Program to demonstrate the above fact

#include<iostream.h>

#include<conio.h>

       class account

              {

                     int acc_no;

                     float balance;

                           public:

                           account()

                                  {

                                         cout<<“Enter the account no: “;

                                         cin>>acc_no;

                                         cout<<“Enter the balance: “;

                                         cin>>balance;

                                  }

                           account(int acc_in)

                                  {

                                         acc_no=acc_in;

                                         balance=0;

                                  }

                           account(int acc_in,float bal)

                                  {

                                         acc_no=acc_in;

                                         balance=bal;

                                  }

                           void display()

                                  {

                                         cout<<“Account number: “<<acc_no<<endl;

                                         cout<<“Balance: “<<balance<<endl;

                                  }

                           void money_transfer(account *acc,float amt);

                     };

       void account::money_transfer(account *acc,float amt)

              {

                     balance=balance-amt;

                     acc->balance=acc->balance+amt;

              }

       void main()

              {

                     clrscr();

                     float trans_amt;

                     account acc1;

                     account acc2(101);

                     account acc3(102,1500);

                     cout<<“Account Information: \n\n”;

                     acc1.display();

                     acc2.display();

                     acc3.display();

              cout<<“How much money is to be transferred from Account3 to Account1?”;

                     cin>>trans_amt;

                     acc3.money_transfer(&acc1,trans_amt);

                     cout<<“\nUpdated balance……….\n\n”;

                     acc1.display();

                     acc2.display();

                     acc3.display();

                     getch();

              }

 

Differences between constructor and destructor

  • Arguments can’t be passed to destructor
  •  Only one destructor can be declared for a given class as a sequence of the fact that destructors cannot have arguments and hence, destructors can’t be overloaded.
  • Destructors can be virtual, while constructors can’t be virtual.

DYNAMIC INITIALIZATION THROUGH CONSTRUCTOR

Object’s data members can be dynamically initialized during run-time, even after their creation. The advantage of this feature is that it supports different initialization formats using overloaded constructors. It provides flexibility of using different forms of data at run-time depending upon the user’s need.

Program to demonstrate the dynamic initialization through constructor

#include<iostream.h>

#include<conio.h>

#include<string.h>

       class details

              {

                     char *f_name;

                     char *m_name;

                     char *l_name;

                           public:

                                  details(char *first);

                                  details(char *first,char *middle);

                                  details(char *first,char *middle,char *last);

                                  void show(char *msg);

              };

       details::details(char *first)

              {

                     strcpy(f_name,first);

                     m_name[0]=l_name[0]=”;

              }

       details::details(char *first,char *middle)

              {

                     strcpy(f_name,first);

                     strcpy(m_name,middle);

                     l_name[0]=”;

              }

       details::details(char *first,char *middle,char *last)

              {

                     strcpy(f_name,first);

                     strcpy(m_name,middle);

                     strcpy(l_name,last);

              }

       void details::show(char *msg)

              {

                     cout<<endl<<msg<<endl;

                     cout<<f_name;

                           if(*m_name)

                                  cout<<m_name;

                           if(*l_name)

                                  cout<<l_name;

              }

       void main()

              {

                     clrscr();

                     details d1(“Ashu”);

                     details d2(“Ashu “,”Akash”);

                     details d3(“Ashu “,”Akash “,”Singh”);

                     d1.show(“First Name”);

                     d2.show(“First and Middle Name”);

                     d3.show(“Full Name”);

                     getch();

              }

 

CONSTRUCTOR WITH DYNAMIC OPERATIONS

A major application of constructors and destructors is in the management of memory allocation during run-time. It will enable a program to allocate the right amount of memory during execution for each object when the object’s data member size is not the same. Allocation of memory to objects at the time of their construction is known as dynamic construction. The allocated memory can be released when the object is no longer needed at run-time and is known as dynamic destruction.

 

 

 

 

 

 

 

 

 

 

 

 

 

Program to demonstrate the constructor with dynamic operations

#include<iostream.h>

#include<conio.h>

       class dynamic

              {

                     int *a;

                     int size;

                           public:

                                  dynamic(int s)

                                         {

                                                size=s;

                                                a=new int[s];

                                         }

                                  ~dynamic()

                                         {

                                                delete a;

                                         }

                                  void get_data()

                                         {

                                                for(int i=0;i<size;i++)

                                                       {

                                                cout<<“Enter elements[“<<i<<“]: “;

                                                              cin>>a[i];

                                                       }

                                         }

                                  void sum()

                                         {

                                                int sum=0;

                                                for(int i=0;i<size;i++)

                                                       {

                                                              sum+=a[i];

                                                       }

                                                cout<<“Sum= “<<sum;

                                         }

              };

       void main()

              {

                     clrscr();

                     int count;

                     cout<<“Enter the number of elements: “;

                     cin>>count;

                     dynamic d1(count);

                     d1.get_data();

                     d1.sum();

                     getch();

              }

 

 

 

 

 

 

 

CONSTRUCTORS FOR TWO-DIMENSIONAL ARRAYS

A class can have multi-dimensional arrays as data-members. Their size can be statically defined or dynamically varied during run-time. A matrix class can be designed to contain data members for storing matrix elements, which are created dynamically.

Program to demonstrate the constructor for two-dimensional array

#include<iostream.h>

#include<conio.h>

#include<process.h>

       class matrix

              {

                     int max_row;

                     int max_col;

                     int **p;

                           public:

                                  matrix()

                                         {

                                                max_row=0;

                                                max_col=0;

                                                p=NULL;

                                         }

                                  matrix(int row,int col);

                                  ~matrix();

                                  void read();

                                  void add(matrix &a,matrix &b);

                                  void sub(matrix &a,matrix &b);

                                  void mult(matrix &a,matrix &b);

                                  int eql(matrix &b);

                                  void show();

              };

       matrix::matrix(int row,int col)

              {

                     max_row=row;

                     max_col=col;

                     p=new int *[max_row];

                           for(int i=0;i<max_row;i++)

                                  p[i]=new int[max_col];

              }

       matrix::~matrix()

              {

                     for(int i=0;i<max_row;i++)

                           delete p[i];

                     delete p;

              }

       void matrix::add(matrix &a,matrix &b)

              {

                     max_row=a.max_row;

                     max_col=a.max_col;

                           if(a.max_row!=b.max_row||a.max_col!=b.max_col)

                                  {

                                         cout<<“Error: Invalid order of addition”;

                                         exit(0);

                                  }

                           for(int i=0;i<max_row;i++)

                                  for(int j=0;j<max_col;j++)

                                         p[i][j]=a.p[i][j]+b.p[i][j];

              }

       void matrix::sub(matrix &a,matrix &b)

              {

                     max_row=a.max_row;

                     max_col=a.max_col;

                           if(a.max_row!=b.max_row||a.max_col!=b.max_col)

                                  {

                                  cout<<“Error: Invalid order of substraction”;

                                         exit(0);

                                  }

                           for(int i=0;i<max_row;i++)

                                  for(int j=0;j<max_col;j++)

                                         p[i][j]=a.p[i][j]-b.p[i][j];

              }

       void matrix::mult(matrix &a,matrix &b)

              {

                     max_row=a.max_row;

                     max_col=b.max_col;

                           if(a.max_col!=b.max_row)

                                  {

                                  cout<<“Error: Invalid order of multiplication”;

                                         exit(0);

                                  }

                           for(int i=0;i<max_row;i++)

                                  for(int j=0;j<max_col;j++)

                                         for(int k=0;k<max_row;k++)

                                                p[i][j]=a.p[i][k]*b.p[k][j];

              }

       int matrix::eql(matrix &b)

              {

                     for(int i=0;i<max_row;i++)

                           for(int j=0;j<max_col;j++)

                                  if(p[i][j]!=b.p[i][j])

                                         return 0;

                                  else

                                         return 1;

              }

       void matrix::show()

              {

                     for(int i=0;i<max_row;i++)

                           {

                                  cout<<endl;

                                  for(int j=0;j<max_col;j++)

                                         {

                                                cout<<p[i][j]<<” “;

                                         }

                           }

              }

       void matrix::read()

              {

                     for(int i=0;i<max_row;i++)

                           {

                                  for(int j=0;j<max_col;j++)

                                         {

                                               cout<<“Matrix [“<<i<<“,”<<j<<“]= “;

                                               cin>>p[i][j];

                                         }

                           }

              }

       void main()

              {

                     clrscr();

                     int r,c,m,n;

                     cout<<“Enter the details of matrix 1:”;

                     cout<<“\nEnter the number of rows: “;

                     cin>>r;

                     cout<<“Enter the number of columns: “;

                     cin>>c;

                     matrix m1(r,c);

                     m1.read();

                     cout<<“Enter the details of matrix 2:”;

                     cout<<“\nEnter the number of rows: “;

                     cin>>m;

                     cout<<“Enter the number of columns: “;

                     cin>>n;

                     matrix m2(m,n);

                     m2.read();

                     cout<<“\nMatrix 1:”;

                     m1.show();

                     cout<<“\n\nMatrix 2:”;

                     m2.show();

                     matrix m3(r,c);

                     m3.add(m1,m2);

                     cout<<“\n\nAddition is:”;

                     m3.show();

                     matrix m4(r,c);

                     m4.sub(m1,m2);

                     cout<<“\n\nSubstraction is:”;

                     m4.show();

                     matrix m5(r,n);

                     m5.mult(m1,m2);

                     cout<<“\n\nMultiplication is:”;

                     m5.show();

                     cout<<“\nIs both matrices are equal:”;

                           if(m1.eql(m2))

                                  cout<<“Yes”;

                           else

                                  cout<<“No”;

                     getch();

              }

 

 

 

 

 

 

For More notes and one to one coaching Contact me : 9905921350

kindly Send your feedback/suggestions/question/doubts