Tuesday 13 November 2012

Functions in C++:

About main function:
In C++, default return type of main function is int.
In C++, if a main function is not prefixed by any return type then it is assumed as int. In such cases if you do not return any int value by using keyword return, a warning occurs during compilation- “Function should return a value”. This situation can be avoided by using return keyword in main or use void before main.

Function Prototype: 
The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and type of return values.

Its syntax is
return type function name (argument list);



Function prototype is also known as function declaration.
If a function is declared outside any function that is globally, then function can be called from any part of the program.
If a function is declared inside a particular function, then it is called local declaration. This means function can be only called from the function where it is declared.



Function Call by Value: 

A function call by passing values
The called function creates a new set of variables and copies the values of arguments into them.
This mechanism is good if the function does not need to alter the values of the original variables in the calling program.



#include<iostream.h> //header file contains declaration of cout and cin
int area(int,int); // function declaration/prototype
void main()
{
int l, b, a;
cout<<“Enter length and breadth”;
cin>>l>>b;
a=area( l , b); //function area() is called by passing two int values
cout<<“Area of rectangle is “<<a;
}
int area(int L, int B) //function definition
{
return(L*B);
}



Here function area() is called by passing two int values, that is mentioned by writing variable names separated by comma in parenthesis.
Values of l and b are copied into variables L and B respectively.
Function can only access its own variables, therefore function area() cannot access l and b. This is the reason we copy value of l and b in L and B.
Function area() returns a value produced by product of L and B. This value is then stored in variable ‘a’ of function main().



Function call by passing address :
There may some scenarios where we would like to change the values of variables in the calling program.
Addresses can always be stored in special variables called pointers.


#include<iostream.h>
main()
{
int a,b;
void swap(int *, int *);
cout<<“Enter two numbers: “;
cin>>a>>b;
swap(&a,&b);
cout<<“a=“<<a<<” b=“<<b;
}
void swap(int *p, int *q)
{
int t;
t=*p;
*p=*q;
*q=t;
}



Above program is of swapping the contents of two variables ‘a’ and ‘b’.
Notice the function call swap(&a, &b), here we pass addresses of variables ‘a’ and ‘b’ in place of values as we want to make changes possible in variable ‘a’ and ‘b’ from function swap().
These addresses get collected in pointers p and q.
swap () function returns nothing as it can directly makes changes in variables a and b using pointers p and q.



Function call by reference: 

A reference is implicit pointers that for all intents and purpose act like another name for a variable.
C++ permits us to pass parameters to the functions by reference.
The formal arguments in the called function become aliases (alternative name) to the actual arguments.

#include<iostream.h>
void main()
{
int a,b;
void swap(int &, int &);
cout<<“Enter two numbers: “;
cin>>a>>b;
swap(a,b);
cout<<“a=“<<a<<” b=“<<b;
}
void swap(int &x, int &y)
{
int t;
t=x;
x=y;
y=t;
}



Here, function swap() is called by passing references of variable ‘a’ and ‘b’.
x and y are reference variables that is another names of ‘a’ and ‘b’ respectively
So we do not create extra copies of ‘a’ and ‘b’.









Inline functions and functions overloadings



Function overloading:
Overloading refers to the use of same thing for different purposes. Function overloading means, we can use the same function name to create functions that perform a variety of different tasks. This is called function polymorphism or compile-time polymorphism in OOP. Another is run time polymorphism which we’ll discuss later 
The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type (return type). 


#include<iostream.h>  
float area(int); 
int area(int,int); 
void main() 
int r; 
cout<<”Enter radius of a circle”; 
cin>>r; 
float a=area(r); 
cout<<”Area of circle is “<<a; 
int l,b,A; 
cout<<”Enter length and breadth of rectangle”; 
cin>>l>>b; 
A=area(l,b); 
cout<<”Area of rectangle is “<<A; 
float area(int R) 
{
 return(3.14*R*R); } 
int area(int L, int B) 
{
 return(L*B); 





Inline function:

Function in a program is to save memory space which becomes appreciable when a function is likely to be called many times.
However every time a function is called, it takes lot of extra time in executing a series of instructions for tasks such as jumping to the functions, saving registers, pushing arguments into the stack and returning to the calling function.
So when function is small it is worthless to spend so much extra time in such tasks in cost of saving comparatively small space.
To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function.
An inline function is a function that is expanded in line when it is invoked.
Compiler replaces the function call with the corresponding function code.
inline is a request not a command.
The benefit of speed of inline functions reduces as the function grows in size.
So the compiler may ignore the request in some situations.

Few of them:
Function containing loops, switch, goto.
Functions with recursion
Containing static variable.



#include<iostream.h>
inline int add(int, int);
void main()
{
int a,b;
cout<<”Enter two numbers”;
cin>>a>>b;
int sum=add(a, b);
cout<<”Sum is “<<sum;
}
int add(int x, int y)
 return(x+y);
}

C++ graphics programs:graphics.h programs


// A program for draw a line.

#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#include<stdio.h>

void main()
{
                int x1,x2,y1,y2,y3;

                int gdriver,gmode;
                gdriver=DETECT;
                initgraph(&gdriver,&gmode,"c:\\tc\\bgi");
                char msg[5];

                gotoxy(18,25);
                cout<<"By Computer Science & Engineering Students)";
                cout<<"\n\t\t\tGuided BY - Shiv Shakti Sir";
                gotoxy(1,0);

                gotoxy(20,1);
                cout<<"****************** LINE ******************\n"<<endl;
                cout<<"Starting pixel cordinate : ";
                cin>>x1>>y1;
                cout<<"Ending pixel cordinate   : ";
                cin>>x2>>y2;
                y3=y2;
                line(x1,y1,x2,y2);

                sprintf(msg," (%d,%d)", x1, y1);
                outtextxy(x1,y1,msg);
                sprintf(msg," (%d,%d)", x2, y3);
                outtextxy(x2,y3,msg);

                getch();

                closegraph();
}





// A program for draw rectangle.

#include<iostream.h>
#include<conio.h>
#include<graphics.h>
#include<stdio.h>

void main()
{
                int x1,y1,width,length;

                int gdriver=DETECT,gmode;
                initgraph(&gdriver,&gmode,"c:\\tc\\bgi");

                setbkcolor(1);
                setcolor(4);

                char msg[5];

                gotoxy(18,25);
                cout<<"By Computer Science & Engineering Students)";
                cout<<"\n\t\t\tGuided BY - Shiv Shakti Sir";
                gotoxy(1,0);


                gotoxy(16,1);
                cout<<"****************** RECTANGLE ******************\n"<<endl;
                cout<<"Sarting cordinate : ";
                cin>>x1>>y1;
                cout<<"Put the length(in pixel) : ";
                cin>>length;
                cout<<"Put the width(in pixel)  : ";
                cin>>width;

                line(x1,y1,x1+length,y1);
                line(x1+length,y1,x1+length,y1+width);
                line(x1+length,y1+width,x1,y1+width);
                line(x1,y1+width,x1,y1);

                getch();

                closegraph();
}

// Ex: starting point (170,120), length (300), width (100).








C++ mini project:Project on ATM machine working


/*program of ATM machine working....*/

#include<string.h>
#include<iostream.h>
#include<conio.h>
class Atm               //classname......//
{
int choice,i;
float b,c;
char str[7];
public:
void get();              //function declaration.....//
};
void Atm::get()
{
cout<<"\tEnter Your Password: ";         //ATM  password(ABCDE)...//
for(i=0;i<=4;i++)
{
str[i]=getch();
cout<<"*";
}
str[i]='\0';
if(strcmp(str,"ABCDE")==0)
{
float a=30000;                         //ATM's front page....//
cout<<endl<<endl<<"\t** WELCOME TO SBI **"<<endl<<endl;
cout<<" \tHello Mr.Manoj Patel\t"<<endl<<endl<<endl;
cout<<"\t1.Information.\t2.Balence inquiry.";
cout<<endl<<endl<<"\t3.Withdrawal\t4.Quit";
cout<<endl<<endl<<endl<<"\t-->please select your choice:";
cin>>choice;
switch(choice)
{
case 1:
cout<<endl<<endl<<"\tName-Pushpendra Pathak"<<endl<<endl;
cout<<"\tAccount no.-0181cs081057"<<endl<<endl<<"\tBranch name-Bhopal";
cout<<endl<<endl<<"\tYour main balence is:"<<a<<endl<<endl<<endl<<"\t\tThank U";
break;
case 2:
cout<<endl<<"\tYour balence is: "<<a<<endl<<endl<<endl<<"\t  Thank U  ";
break;
case 3:
cout<<endl<<"\tyour balence is: "<<a<<endl;
cout<<endl<<"\tPlease enter your ammount:";
cin>>b;
if(b>a)
{
cout<<endl<<endl<<"\tyou have not sufficient balence";
goto out;
}
else
{
c=a-b;
cout<<endl<<endl<<"\tyou have withdrawn Rs. "<<b;
cout<<endl<<endl<<"\tYour balence now:"<<c<<endl<<endl<<"\tThank U";
break;
}
out:
default:
cout<<endl<<endl<<"\tThank U";
}
}
else
{
cout<<endl<<endl<<"\tPassword incorrect";
cout<<endl<<endl<<"\tThank U";
 }
}
void main()
{
clrscr();
Atm A;
A.get();
getch();
}


Inheritance in C++


 Inheritance:

 In C++, inheritance is the mechanism by which one class can inherit the properties of another.
 When one class is inherited by another, the class that is inherited is called the base class. The inheriting class is called derived class.
 Base class is also known as parent class or old class. Derived class is also known as child class or new class.
 Remember constructor never inherits.
 Structure in C++ also supports inheritance.

Syntax for inheritance:

class base-name
{
  …
};
class derived-name : visibility mode base-name
{
 …
};

 Syntax covers two classes, one is base class and other is derived class.
 During derived class definition, notice a colon (:) followed by visibility mode and then comes base class name. This addition to derived class definition tells the compiler about linking between two classes.
 Members of base class now also consider members of derived class.
 Membership category for the base class members in derived class are defined by visibility mode.
 Visibility modes are private, protected and public.
 In class, when no visibility mode is mentioned, it is private by default.
 In structure, when no visibility mode is mentioned, it is public by default.

Visibility Modes:

 Whatever may the visibility mode, private members of base class never inherits.
 When visibility mode is private, all protected and public members of base class become private members of derived class.
 When visibility mode is protected, all protected and public members of base class become protected members of derived class.
 When visibility mode is public, all protected members of base class become protected members of derived class and all public members of base class become public members of derived class.



Advantages of inheritance:

 Reusability
 Saves time and efforts
 Increases program structure which results in greater reliability.
 It implements generalization and specialization

Types of inheritance:

There are five types of inheritance:

1) Single inheritance
When there is one parent class and one child class inheriting properties from base class, known as single inheritance.

Syntax:

class Base
{….};
class Derived: visibility mode Base
{….};

2) Multilevel inheritance
When a child class becomes parent of other class, it increases level of inheritance and known as multilevel inheritance.

Syntax

class A
{….};
class B: visibility-mode A
{….};
class C: visibility- mode B
{….};

3) Multiple inheritance
When a child class has more than one parent class, it is known as multiple inheritance.

Syntax

class A1
{….};
class A2
{….};
class B: visibility- mode A1, visibility-mode A2
{….};

4) Hierarchical inheritance
When a base class has more than one child classes, it is known as hierarchical inheritance.

Syntax

class A
{….};
class B1: visibility-mode A
{….};
class B2: visibility- mode A
{….};

5) Hybrid inheritance
A single structure of classes obtained from more than one type of inheritance is known as hybrid inheritance.

Syntax

class A
{….};
class B1: visibility-mode A
{….};
class B2: visibility- mode A
{….};
class C: visibility-mode B1, visibility-mode B2
{….};


Constructors in inheritance:
 Always remember constructor never inherits
 As long as no base class constructor takes any arguments, the derived class need not have a constructor function. However if any base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructors.
 When both the derived and base classes contain constructors, the base constructor is executed first and then the constructor in the derived class is executed.
 In multilevel inheritance the constructor will be executed in the order of inheritance. In case of multiple inheritance the base class are constructed in the order in which they appear in the declaration of the derived class.

Syntax:

Derived-constructor(arglist1,arglist2,…,arglist d) :
 base1(arglist1), base2(arglist2),…
{
  …
  …  //argument list d is used here(base constructor’s
  …            //definition
  …
}



Destructor in inheritance

Just like constructors destructors also non inheritable members. Their execution order is reverse the execution order of constructors. This means child class destructors executes first and followed by parent class destructors.


Function Overriding:

During inheritance when base class and derived class both shares a common function name in their respective class two situations encounters:
First scenario when a function in derived class has same name as of function in base class with same prototype. This is called function overriding.
Whenever this function s called using child class object child class version will be invoked.
To invoke base class version we need to specify class name and scope resolution operator.
Following example enlighten this fact.

#include<conio.h>
#include<iostream.h>
class Base
{
  public:
     void msg()
     {
          cout<<” Base Message”;
     }
};
class Derived : public Base
{
   public:
void msg()
     {
          cout<<” Derived Message”;
     }

};
void main()
{
  Derived O;
  O.msg(); //Derived class msg() executes
  O.Base::msg(); //Base class msg() executes
}


Function Hiding:

Second scenario is when base and derived class share same function name but different prototypes. In such case it can not be considered as function overloading as functions are in different scopes. Here, we say function hiding.

#include<conio.h>
#include<iostream.h>
class Base
{
  public:
     void msg(int k)
     {
          cout<<” Base Message”<<k;
     }
};
class Derived : public Base
{
   public:
void msg()
     {
          cout<<” Derived Message”;
     }

};
void main()
{
  Derived O;
  O.msg(); //Derived class msg() executes
  O.Base::msg(3); //Base class msg() executes
  O.msg(3); //error as derived msg() hides base msg(int)
}

Virtual base class:

A special scenario arises during hybrid inheritance. First to let us understand problem consider the following example

#include<conio.h>
#include<iostream.h>
class A
{
     public:
          void fun_a()
          {
              cout<<”Function of Class A”;
          }
};
class B1: public A
{
     public:
          void fun_b1()
          {
              cout<<”Function of Class B1”;
          }
};
class B2: public A
{
     public:
          void fun_b2()
          {
              cout<<”Function of Class B2”;
          }
};
class C: public B1, public B2
{
     public:
          void fun_c()
          {
              cout<<”Function of Class A”;
          }
};
void main()
{
   C O1;
   O1.fun_c(); //valid
   O1.fun_b1(); //valid as publicly inherited from base B1
   O1.fun_b2(); // valid as publicly inherited from base B2
   O1.fun_a(); //error: ambiguity between two copies of function in class C inherited twice // via class B1 and B2
}

Since function fun_a() of parent most class A is inherited twice in class C, first via class B1 and second via class B2. This makes two copies of the same function in child most class C and can not be resolved function call due to identical prototype. This leads to an ambiguity error.

Solution of the above problem is to make parent most class as virtual base class of class C. This means class A will now become virtually parent class of class C, instead of grant parent.

During definition of intermediate base classes B1 and B2, we mention keyword virtual to make parent class A virtual base class of child class of B1 and B2. Now only one copy of function fun_a() will be available for class C.

Following example illustrates syntactical part of virtual base class:
#include<conio.h>
#include<iostream.h>
class A
{
     public:
          void fun_a()
          {
              cout<<”Function of Class A”;
          }
};
class B1: virtual public A
{
     public:
          void fun_b1()
          {
              cout<<”Function of Class B1”;
          }
};
class B2: public virtual A
{
     public:
          void fun_b2()
          {
              cout<<”Function of Class B2”;
          }
};
class C: public B1, public B2
{
     public:
          void fun_c()
          {
              cout<<”Function of Class A”;
          }
};
void main()
{
   C O1;
   O1.fun_c(); //valid
   O1.fun_b1(); //valid as publicly inherited from base B1
   O1.fun_b2(); // valid as publicly inherited from base B2
   O1.fun_a(); // valid as only one copy of function in //class C
}

  

C++ keywords

C++ Keywords: 

auto                  declare a local variable
bool                  declare a boolean variable
break                break out of a loop
case                  a block of code in a switch statement
catch                 handles exceptions from throw
char                  declare a character variable
class                 declare a class
const                declare immutable data or functions that do not change data
const_cast        cast from const variables
continue            bypass iterations of a loop
default              default handler in a case statement
delete               make memory available
do                    looping construct
double             declare a double precision floating-point variable
dynamic_cast   perform runtime casts
else                 alternate case for an if statement
enum               create enumeration types
explicit            only use constructors when they exactly match
export             allows template definitions to be separated from their declarations
extern              tell the compiler about variables defined elsewhere
false                the boolean value of false
float                declare a floating-point variable
for                   looping construct
friend              grant non-member function access to private data
goto                jump to a different part of the program
if                     execute code based off of the result of a test
inline               optimize calls to short functions
int                   declare a integer variable
long                declare a long integer variable
mutable           override a const variable
namespace      partition the global namespace by defining a scope
new                allocate dynamic memory for a new variable
operator         create overloaded operator functions
private            declare private members of a class
protected       declare protected members of a class
public             declare public members of a class
register           request that a variable be optimized for speed
return             return from a function
short              declare a short integer variable
signed            modify variable type declarations
sizeof             return the size of a variable or type
static              create permanent storage for a variable
static_cast      perform a nonpolymorphic cast
struct             define a new structure
switch            execute code based off of different possible values for a variable
template         create generic functions
this                 a pointer to the current object
throw             throws an exception
true                the boolean value of true
try                  execute code that can throw an exception
typedef          create a new type name from an existing type
typeid            describes an object
typename       declare a class or undefined type
union             a structure that assigns multiple variables to the same memory location
unsigned        declare an unsigned integer variable
using              import complete or partial namespaces into the current scope
virtual            create a function that can be overridden by a derived class
void               declare functions or data with no associated data type
volatile           warn the compiler about variables that can be modified unexpectedly
wchar_t         declare a wide-character variable
while              looping construct

Generic function and Class Template in c++

Generic function and Class Template
C++ templates can be used both for classes and for functions in C++.

Function Template
Function template is also known as generic function
The main advantage of function overloading is that you can use same name of function for performing similar tasks in different parts of a program.
If you want to accommodate more data types, you will require additional versions of function. This is the main disadvantage of function overloading.
However, C++ compilers have a facility called template which will help you create only one version of function. This version will accommodate different data types of C++. A function which works for all data types of C++ is called a generic function or a function template.
Syntax is:template <class type> type func_name(type arg1, ...);
type is any name of your choice, which is a placeholder name for a data type used by the function. The name X is replaced by actual data type when the compiler creates a specific version of the function.

Example
#include<iostream.h>
#include<conio.h>
template <class X> X big(X a, X b)
{
return ((a>b)?a:b);
}
void main()
{
cout<<”\n Bigger of two is: ”<<big(21,16)<<”\n”;
cout<<”\n Bigger of two is: ”<<big(13.44, 16.54)<<”\n”;
cout<<”\n Bigger of two is: ”<<big(‘E’, ‘L’)<<”\n”;
}


The output look like:
Bigger of two is: 21
Bigger of two is: 16.54
Bigger of two is: L



Generic Class or Class Template

Syntax


template <class X> class class-name
{


}



Example

#include<conio.h>
#include<iostream.h>
template <class X> class xyz
{
X pdata;
public:
xyz() { }
xyz(X n)
{
pdata=n;
}
void show()
{
cout<<pdata;
}
~xyz() { }
};
void main()
{
clrscr();
xyz<int> data1(20);
cout<<"\n data1=";
data1.show();
xyz<int> data2;
data2=data1;
cout<<"\ndata2= ";
data2.show();
xyz<float> data3(195.05);
cout<<"\ndata3 = ";
data3.show();
xyz<long> data4(356432L);
cout<<"\ndata4=";
data4.show();
getch();
}

Explanation
To make class generalize in terms of data type we can make class template
Here X is a place holder for data type.
Notice the way object is created data type for the place holder must be mentioned in angular brackets.
It is obvious that the size of object depends on data type for place holder.

C++ Sample programs


Input/Output Instruction

In C, standard input device is keyboard and scanf() is use to receive data from keyboard.
Also, standard output device is monitor and printf() is use to send data/message to monitor.

In C++, printf() can be replaced by ‘cout’:
 cout<<”Hello RAM”;
 This statement introduces two new C++ features, cout and <<.
 cout is a predefined object.
 The operator << is called the insertion or put to operator
 It is used to display message on the screen.

Examples:
printf(“Hello RAM”);
cout<<“Hello RAM”;
printf(“sum of %d and %d is %d”, a, b, c);
cout<<“sum of ”<<a<<“ and “<<b<<“ is “<<c;
printf(“%d”,a+b);
cout<<a+b;



In C++, scanf() can be replaced by ‘cin’:
 cin>>x;
 cin>>y>>z;
 The identifier cin is a predefined object in C++
 The operator >> is known as extraction or get from operator
 It is used to take input from keyboard.

Examples:
scanf(“%d”, &a);
cin>>a;
scanf(“%d%d”, &a, &b);
cin>>a>>b;
scanf(“%d%f”, &a, &c);
cin>>a>>c;


About header file iostream.h
We need to include header file iostream.h, as it contains declarations for the identifier cout and the operator <<. Also it contains declarations for the identifier cin and operator >>.


Sample Program: 
#include<iostream.h>
void main()
{
int x, s;
cout<<”Enter a number”;
cin>>x;
s=x*x;
cout<<”Square of “<<x<<” is “<<s;
}