0% found this document useful (0 votes)
26 views31 pages

Template

cpp notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views31 pages

Template

cpp notes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

class polar

double theta,r;

public:

polar ()

theta=0;

r=0;

operator rectangular()

double x,y;

//float atheta=theta*pi/180;

x=r*cos(theta);

y=r*sin(theta);

return rectangular(x,y);

void output()

cout<<"\nr="<<r;

cout<<"\ntheta="<<theta;

};

Compiled By: Mohan Bhandari, Ranjan Adhikari


int main()

rectangular r1,r2;

polar p1(3,45);
r1=p;// polar to rectangular conversion
r1.display();
}

Example:
/* Program to convert class Time to another class Minute.

#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
class Time
{
int hrs,min;
public:
Time(int h,int m)
{
hrs=h;
min=m;
}
Time()
{
cout<<"\n Time's Object Created";
}
int getMinutes()
{
int tot_min = ( hrs * 60 ) + min ;
return tot_min;
}
void display()
{
cout<<"Hours: "<<hrs<<endl ;
cout<<" Minutes : "<<min <<endl ;
}
};
class Minute
{
int min;
public:

Minute()
{
min = 0;

Compiled By: Mohan Bhandari, Ranjan Adhikari


}
void operator=(Time T)
{
min=T.getMinutes();
}
void display()
{
cout<<"\n Total Minutes : " <<min<<endl;
}
};
void main()
{
clrscr();
Time t1(2,30);
t1.display();
Minute m1;
m1.display();

m1 = t1; // conversion from Time to Minute

t1.display();
m1.display();
getch();
}

Polymorphic Variable (Assignment Polymorphism):


The variable that can hold different types of values during the course of execution is called polymorphic variable. It can
also be defined as the variable that is declared as one class and can hold values from subclass. In C++, it works with
pointers and references. Pure polymorphism means a function with polymorphic variable as arguments (or
parameters).

This Pointer
If only one copy of each member function exists and is used by multiple objects, then for proper data members
accessing and updating, Compiler supplies an implicit pointer along with the functions names as this . this pointer is
an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the
invoking object. Friend functions do not have this pointer, because friends are not members of a class. Only member
functions have this pointer.
Following are the situations where this pointer is used:
1) When local variable’s name is same as member’s name
#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x

Compiled By: Mohan Bhandari, Ranjan Adhikari


// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}

2) To return reference to the calling object


#include<iostream>
using namespace std;
class Test
{
private:
nt x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
est &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
Test obj1(5, 5);

// Chained function calls. All calls modify the same object


// as the same object is returned by reference
obj1.setX(10).setY(20);

obj1.print();
return 0;
}

Method overriding
Function overriding is a feature that allows us to have a same function in child class which is already present
in the parent class. A child class inherits the data members and member functions of parent class, but when
you want to override a functionality in the child class then you can use function overriding. It is like creating
a new version of an old function, in the child class.

#include <iostream>

using namespace std;

class BaseClass {

Compiled By: Mohan Bhandari, Ranjan Adhikari


public:

void disp()
{
cout<<"Function of Parent Class";
}

};

class DerivedClass: public BaseClass{

public:

void disp() // it overrides the method of class Baseclasss


{
cout<<"Function of Child Class";
}
};

Compiled By: Mohan Bhandari, Ranjan Adhikari


Chapter 6
Template and generic programming

Template
 Templates are the foundation of generic programming, which involves writing code in a way that is
independent of any type.
 A template is a blueprint or formula for creating a generic class or a function.
 A template is one of the recently added feature in C++. It supports the generic data types and generic
programming.
 Generic programming is an approach where generic data types are used as parameters in algorithms so that
they can work for a variety of suitable data types.
Example:
i. A class template for an array class would enable us to create arrays of various data types such as int
array and float array.
ii. A function template say mul() can be used for multiplying int, float and double type values.
 A Template can be considered as Macro. When an object of specific type is defined for actual use, the
template definition for that class is substituted with the required data type.
 Since a template is defined with a parameter that would be replaced by a specified data type at the time of
actual use of the class or function, the template is also called as parametrized class or functions.

Features of Template
i. Templates are easier to write. We can create only one generic version of our class or function instead
of manually creating specializations.
ii. Templates are easier to understand, since they provide a straightforward way of abstracting type
information.
iii. Templates are type safe. Because the types that templates act upon are known at compile time, the
compiler can perform type checking before errors occur.

Class Template
The general form of a generic class declaration is shown here:
template<classgeneric_data_type>
class class-name
{
…………………..
}

Advantage of class Template


i. One C++ Class Template can handle different types of parameters.
ii. Compiler generates classes for only the used types. If the template is instantiated for int type, compiler
generates only an int version for the C++ template class.

Compiled By: Ranjan Adhikari, Mohan Bhandari


iii. Templates reduce the effort on coding for different data types to a single set of code.
iv. Testing and debugging efforts are reduced.

Disadvantage of Template
i. Many compilers historically have very poor support for templates, so the use of templates can make
code somewhat less portable.
ii. Almost all compilers produce confusing, unhelpful error messages when errors are detected in
template code. This can make templates difficult to develop
iii. Each use of a template may cause the compiler to generate extra code (an instantiation of the
template), so the indiscriminate use of templates can lead to code bloat,
resulting in excessively large executable.
Example:
1. WAP to demonstrate the concept of generic class.
#include<iostream>
using namespace std;
template<class T>
class Demo
{
private:
T x;
public:
Demo( T p)
{
x=p;
}
void show()
{
cout<<"\n"<<x;
}
};
int main()
{
Demo <char *>p1("Ram");
Demo <char> p2 ('A');
Demo <int> p3(5);
Demo <float>p4 (5.5);
p1.show ();
p2.show ();
p3.show ();
p4.show ();

Compiled By: Ranjan Adhikari, Mohan Bhandari


}
Output:
Ram
A
5
5.5

2. WAP to find the area of circle using the concept of generic class.
#include <iostream>
using namespace std;
template<class T> // here T is generic data type
class Rectangle
{
private:
T len,bre;
public:
Rectangle(T l, T b)
{
len=l;
bre=b;
}
T area()
{
return(len*bre);
}
};
int main()
{
Rectangle<int>r1(4,5);
cout<<"Area= "<<r1.area()<<endl;
Rectangle <float>r2(4.5, 2.5);
cout<<"Area= "<<r2.area()<<endl;
}

In the above program, to define a class template Rectangle, we must prefix its definition by template<class
T>. This prefix tells the compiler that we are going to declare a template and use T as a type name in the class
definition. Thus, Rectangle has become parameterized class with T as its parameter. So, T can be substituted
by any data type like int, float or any user defined data type.
Here in the example the statement Rectangle<int>r1(4,5); initialize T as int type and hence the class
constructor receive integer type argument and method T area() also returns integer type value. Similarly, the
statement Rectangle <float>r2(4.5, 2.5); initialize T as float type and hence the class constructor receive
floating type argument and method T area() also returns Floating type value

Or , we can write the same program as below:

#include <iostream>
using namespace std;
template<class T> // here T is generic data type
class Rectangle
{
private:
T len,bre;

Compiled By: Ranjan Adhikari, Mohan Bhandari


public:
setdata(T x, T y)
{
len=x;
bre=y;
}
T area()
{
return(len*bre);
}
};
int main()
{
Rectangle<int> r1;
r1.setdata(4,5);
cout<<"Area= "<<r1.area()<<endl;
Rectangle <float> r2;
r2.setdata(4.5,2.5);
cout<<"Area= "<<r2.area()<<endl;
}

3. WAP to find the sum of two complex number using the concept of generic class.
#include <iostream>
using namespace std;
template<class T>
class complex
{
T real;
T img;
public:
complex()
{
real=0;
img=0;
}
complex(T f1, T f2)
{
real=f1;
img=f2;
}

complex sum(complex tmp)


{
complex result;
result.real = tmp.real+real;
result.img = tmp.img+img;
return result;
}

void show()
{
cout<<"Real= "<<real<<endl;
cout<<"Imaginary= "<<img<<endl;
}
};

int main()
{
//finding the sum of two integer complex number

Compiled By: Ranjan Adhikari, Mohan Bhandari


complex<int> c1(3,6);
complex<int> c2(2,-2);
complex<int> c3;//will invoke default constructor
c3=c1.sum(c2);
c3.show();

//finding the sum of two float complex number


complex<float> c4(3.5,6.0);
complex<float> c5(2.5,-2.5);
complex<float> c6;//will invoke default constructor
c6=c4.sum(c5);
c6.show();
}

4. WAP to find the sum of two complex number using the concept of generic class and operator overloading.
#include <iostream>
using namespace std;
template<class T>
class complex
{
T real;
T img;
public:
complex()
{
real=0;
img=0;
}

complex(T f1, T f2)


{
real=f1;
img=f2;
}

complex operator +(complex tmp)


{
complex result;
result.real = tmp.real+real;
result.img = tmp.img+img;
return result;
}
void show()
{
cout<<"Real= "<<real<<endl;
cout<<"Imaginary= "<<img<<endl;
}
};

int main()
{
//finding the sum of two integer complex number
complex<int> c1(3,6);
complex<int> c2(2,-2);
complex<int> c3;//will invoke default constructor
c3=c1+c2; // equivalent to c3=c1.operator +(c2);
c3.show();

Compiled By: Ranjan Adhikari, Mohan Bhandari


//finding the sum of two float complex number
complex<float> c4(3.5,6.0);
complex<float> c5(2.5,-2.5);
complex<float> c6;//will invoke default constructor
c6=c4+c5; // equivalent to c6=c4.operator+(c5);
c6.show();
}

Class Template with multiple parameters


When we have to use more than one generic data type in a class template, it can be achieved by using a comma-
separated list within the template specification as below.
template<class T1, class T2………class TN>
Class class_name
{

};
Example:
#include <iostream>
using namespace std;
template<class T1, class T2 >
class Demo
{
private:
T1 a;
T2 b;
public:
Demo(T1 x, T2 y)
{
a=x;
b=y;

}
void show()
{
cout<<"A= "<<a<<endl;
cout<<"B= "<<b<<endl;
}
};
int main()
{
Demo<int,float> d1(1,4.5);
d1.show();

Demo<char,int> d2('B',6);
d2.show();

Demo <char *, float>d3("bhesh",6);


d3.show();
}

Compiled By: Ranjan Adhikari, Mohan Bhandari


Function Template
Like class, we can also define function templates that can be used to create a family of functions with different
arguments types. The general format for function template is given below
template<class T>
returnType of type Tfunction_name (argument of type T)
{
//body of function with type T whenever appropriate
}
Note: Main function can’t be declared as template
Example:
1. WAP to declare template function that can be used to find the area of rectangle.
#include<iostream>
using namespace std;
template<class t>
t area(t len, t bre)
{
return(len*bre);
}
int main()
{
int l1=6,b1=4;
cout<<"Area= "<<area(l1,b1)<<endl;
float l2=2.5,b2=2.0;
cout<<"Area= "<<area(l2,b2);
}

2. WAP to declare a function template that can be used to swap two values of a given type of data.
//using concept of pointer
#include <iostream>
using namespace std;
template<class T >
void swap( T *fn, T *sn )
{
T tmp;
tmp=*fn;
*fn=*sn;
*sn=tmp;
}

int main()
{
int m=5,n=6;
cout<<"Before swapping"<<endl;
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
swap(&m,&n);
cout<<"After swapping"<<endl;
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
}

Compiled By: Ranjan Adhikari, Mohan Bhandari


Or
//Using concept of reference variable
#include <iostream>
using namespace std;
template<class T >
void swap( T &fn, T &sn )
{
T tmp;
tmp=fn;
fn=_sn;
fn=tmp;
}

int main()
{
int m=5,n=6;
cout<<"Before swapping";
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
swap(m,n);
cout<<"After swapping";
cout<<"M= "<<m<<endl<<"N= "<<n<<endl;
}

3. Create a function template that can be used to find the maximum numbers among 10 numbers of given type of
data(int, float etc)
#include <iostream>
using namespace std;
template<class T >
T Max( T data[] )
{
T great=data[0];
for(inti=0;i<10;i++)
{
if(data[i]>great)
great=data[i];
}
return great;
}

int main()
{
int a[10]={4,3,7,9,8,5,88,34,23,11};
cout<<"Largest number= "<<Max(a)<<endl;

float b[10]={4.5,3.6,7.6,99.8,8,5,88.8,34.3,23.5,11.5};
cout<<"Largest number= "<<Max(b);
}

4. Create a function templates that can be used to find the minimum and maximum numbers among 10 numbers
of given type of data(int, float etc)
#include <iostream>
using namespace std;
template<class T >
T Max( T data[] )
{
T great=data[0];
for(inti=0;i<10;i++)
{
if(data[i]>great)

Compiled By: Ranjan Adhikari, Mohan Bhandari


great=data[i];
}
return great;
}

template<class T >
T Min( T data[] )
{
T small=data[0];
for(inti=0;i<10;i++)
{
if(data[i]<small)
small=data[i];
}
return small;
}

int main()
{
int a[10]={4,3,7,9,8,5,88,34,23,11};
cout<<"Largest number= "<<Max(a)<<endl;
cout<<"Smallest number= "<<Min(a)<<endl;

float b[10]={4.5,2.6,7.6,99.8,8,5,88.8,34.3,23.5,11.5};
cout<<"Largest number= "<<Max(b)<<endl;
cout<<"Smallest number= "<<Min(b)<<endl;
}

5. Create a function template to add two matrices.


#include<iostream>
using namespace std;
template<class t>
void add(t x [][10], t y [][10], t row, t col)
{
tsm[10][10];
for(inti=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
sm[i][j]=x[i][j]+y[i][j];
}
}
for(inti=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cout<<sm[i][j]<<" ";
}
cout<<endl;
}
}

int main()
{
int m[10][10],n[10][10],row,col;
cout<<"Enter the number of rows and column"<<endl;
cin>>row>>col;
cout<<"Enter the elements of first matrix"<<endl;
for(inti=0;i<row;i++)

Compiled By: Ranjan Adhikari, Mohan Bhandari


{
for(int j=0;j<col;j++)
{
cin>>m[i][j];
}
}
cout<<"Enter the elements of second matrix"<<endl;
for(inti=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cin>>n[i][j];
}
}
add(m,n,row,col);
}

Function template with multiple parameters


Like template class, we can use more than one generic data type in the template statement, using a comma separated
list as shown below.
template<class t2, class t2………>
Return_typefunction_name(arguments of types T1, T2……..)
{

}
Example:
#include <iostream>
using namespace std;
template<class T1, class T2 >
void show(T1 x, T2 y)
{
cout<<"First Parameter= "<<x<<endl;
cout<<"Second Paramter= "<<y<<endl;
}
int main()
{
show(1,2);
show(1.4,3.5);
show('r',"Ram");
}

Overloading of Template Function


A template function can be overloaded either by template functions or ordinary functions of its name.In such case,
overloading resolution is accomplished as follows
i. Calling an ordinary function that has an exact match.
ii. Calling a template function that could be created with an exact match.
iii. Trying normal overloading resolution to ordinary functions and call the one that matches.
An error is generated if no match is found. Also no automatic conversion are applied to arguments on the template
function.

Compiled By: Ranjan Adhikari, Mohan Bhandari


Example:

#include<iostream>
using namespace std;
template<class t>
void display(t x)
{
cout<<"From Template Function X= "<<x<<endl;
}

template<class t1, class t2>


void display(t1 x, t2 y)
{
cout<<"From Template Function"<<endl<<"X= "<<x<<endl<<"Y= "<<y<<endl;
}
void display(float x)
{
cout<<"From Ordinary Function X= "<<x<<endl;
}
void display(float x, float y)
{
cout<<"From Ordinary Function"<<endl<< "X= "<<x<<endl<<"Y= "<<y<<endl;
}

int main()
{
display(100);//will invoke template function with one argument as no exact matching ordinary function exist.
display(100.5f);// will invoke ordinary function as exact matching ordinary function exist
display(2.4f,3.5f);//will invoke ordinary function as exact matching ordinary function exist
display(3,5);//will invoke template function with two argument because non ordinary function matches this signature
}

Example 2:

#include<iostream>
using namespace std;
void display(float x)
{
cout<<"From Ordinary Function1 X= "<<x<<endl;
}

template<class t1, class t2>


void display (t1 x, t2 y)
{
cout<<"From template Function X= "<<x<<" Y= "<<y<<endl;
}

int main()
{
display(100); //will invoke ordinary function1 with one argument of type float(i.e. int casted to
float)
display("bhesh",5);

Compiled By: Ranjan Adhikari, Mohan Bhandari


}

Exception Handling in C++


Introduction to error
In computing, an error in a program is due to the code that does not conform to the order expected by the
programming language. An error may produce and incorrect output or may terminate the execution of program
abruptly or even may cause the system to crash.
Types of Errors
i. Compile Time Error
ii. Runtime Error

Compile Time Error


At compile time, when the code does not comply with the C++ syntactic and semantics rules, compile-time errors will
occur. The goal of the compiler is to ensure the code is compliant with these rules. Any rule-violations detected at this
stage are reported as compilation errors. These errors are checked.
The following are some common compile time errors:
 Writing any statement with incorrect syntax
 Using keyword as variable name
 Attempt to refer to a variable that is not in the scope of the current block
 A class tries to reference a private member of another class
 Trying to change the value of an already initialized constant (final member)
etc……….

Runtime Error
When the code compiles without any error, there is still chance that the code will fail at run time. The errors only
occur at run time are call run time errors. Run time errors are those that passed compiler’s checking, but fail when the
code gets executed. These errors are unchecked.
The following are some common runtime errors:
 Divide by zero exception
 Array index out or range exception
 StackOverflow exception
 Dereferencing of an invalid pointer
etc……….
So, runtime errors are those which are generally can’t be handled and usually refers catastrophic failure.

Exception
An exception is a run-time error. Proper handling of exceptions is an importantprogramming issue. This is because
exceptions can and do happen in practice andprograms are generally expected to behave gracefully in face of such
exceptions.
Unless an exception is properly handled, it is likely to result in abnormal programtermination and potential loss of
work. For example, an undetected division by zeroor dereferencing of an invalid pointer will almost certainly
terminate the programabruptly.
Types
1. Synchronous: Exception that are caused by events that can be control of program is called synchronous
exception. Example, array index out or range exception.
2. Asynchronous: Exception that are caused by events beyond the control of program is called synchronous
exception. Example, Exception generated by hardware malfunction.

Compiled By: Ranjan Adhikari, Mohan Bhandari


Basic steps in exception handling

The purpose/Use of exception handling mechanism is to provide means to detect and report an exception so that
appropriate actions can be taken. Exception handling mechanism in C++ consists of four things:
i. Detecting of a run-time error (Hit the exception)
ii. Raising an exception in response to the error (Throw the exception)
iii. Receive the exception information (Catch the exception)
iv. Taking corrective action. (Handle the exception)
C++ provides a language facility for the uniform handling of exceptions. Underthis scheme, a section of code whose
execution may lead to run-time errors islabeled as a try block. Any fragment of code activated during the execution of
atry block can raise an exception using a throw clause. All exceptions are typed(i.e., each exception is denoted by an
object of a specific type). A try block isfollowed by one or more catch clauses. Each catch clause is responsible for
thehandling of exceptions of a particular type.When an exception is raised, its type is compared against the catch
clausesfollowing it. If a matching clause is found, then its handler is executed. Otherwise,the exception is propagated
up, to an immediately enclosing try block (if any). Theprocess is repeated until either the exception is handled by a
matching catch clauseor it is handled by a default handler.
The general form is as below:
……….
……….
try
{
…..
…..
throw exception; //block of statements which detect and throws an exception
}
catch(type arg) //catches exception
{
…..
…. //block of statements that handle the exception
…..
}
…….
…….

Example:
WAP to input two number and divide first number by second. The program must handle the divide by zero exception.

Compiled By: Ranjan Adhikari, Mohan Bhandari


#include<iostream>
using namespace std;
int main()
{
intnu,de,res;
cout<<"Enter numerator and denominator";
cin>>nu>>de;
try
{
if(de==0)
{
throw(de); //throw int object
}
else
{
res=nu/de;
cout<<"Result= "<<res;
}
}
catch(inti) //catches the int type exception
{
cout<<"Divide by zero exception occurred: de= "<<i;
}
}

So, in the above program, when no exception is thrown, the catch block is skipped and outputs correct result. But
when the user input zero for denominator, the exception is thrown using throw statement with int type object as
argument. Since the exception object type is int, the exception handler i.e. catch statement containing int type
argument catches the exception and handles it by displaying necessary message or performing necessary steps further.
Note:
i. During execution, when throw statement is encountered, then it immediately transfers the control suitable
exception handler i.e. catch block. Hence all the statement after throw in try block are skipped.
ii. If there are multiple catch block with integer type argument, then the first one immediately after try block
gets executed.
iii. When an exception object is thrown and non of the catch block matches, the program is aborted with the
help of abort() function which is invoked automatically.

Invoking function that generates Exception


Exceptions can also be thrown from function that are invoked from within the try block. The point at which throw is
executed is called throw point. Once an exception is thrown to the catch block, control can’t return to the throw point.
The general form is:
typefunction_name(arg list) // Function with exception
{
Throw (object); // throws an exception
}
……….
……….
try
{
…………
………… // function is invoked from here
………….
}
catch(type org) //caches exception

Compiled By: Ranjan Adhikari, Mohan Bhandari


{
…………
………… //handles the exception here
…………
}

Example:
#include<iostream>
using namespace std;
int divide(int,int);
int main()
{
intnu,de,res;
cout<<"Enter numerator and denominator";
cin>>nu>>de;
try
{
res=divide(nu,de);
cout<<"Result= "<<res;
}

catch(inti) //catches the int type exception


{
cout<<"Divide by zero exception occurred: de= "<<i;
}
}
int divide(intfn, intsn)
{
if(sn==0)
{
throw(sn);
}
else
{
return(fn/sn);
}
}

Nesting try statement


A try block can be placed inside the block of another try, called as nested try.

Example:
WAP to input two numbers and divide first number by second. The result must be stored in the index entered by user.

#include<iostream>
using namespace std;
int divide(int,int);

int main()
{

Compiled By: Ranjan Adhikari, Mohan Bhandari


inta,b,ind,res;
int c[10];
cout<<"Enter numerator and denominator"<<endl;
cin>>a>>b;
try
{
if(b==0)
{
throw(b);
}
cout<<"Enter the index to store the result";
cin>>ind;
try
{
if(ind>=10)
{
throw(ind);
}
res=a/b;
c[ind]=res;
cout<<"Result "<<res<<" successfully stored at index "<<ind;
}
catch(int e)
{
cout<<"Index out of range exception occurred: index= "<<ind;
}
}
catch(int e )
{
cout<<"Divide by zero exception occured: b="<<b;
}
}

Multiple catch statement


It is also possible that a program segment has more than one condition to throw an exception. In such cases, we can
associate more than one catch statement with a try as shown below.
try
{
catch(type1object);
catch(type2object);
……………………
catch(typeNobject);
}
catch(type1 arg)
{

Compiled By: Ranjan Adhikari, Mohan Bhandari


catch(type2 arg)
{

}
catch(typeNarg)
{

Example:
#include<iostream>
using namespace std;
int divide(int,int);
int main()
{
try
{
doublenu,de,res[10],c;
intind;
cout<<"Enter numerator and denominator"<<endl;
cin>>nu>>de;
if(de==0)
{
throw(de);
}
cout<<"Enter the index to store the result"<<endl;
cin>>ind;
if(ind>=10)
{
throw(ind);
}
c=nu/de;
res[ind]=c;
cout<<"Result= "<<c<<" Successfully stored at "<<ind<<" posiion";
}
catch(int a)
{
cout<<"Index out or range exception: Index= "<<a;
}
catch(double d)
{
cout<<"Divide by zero exception: Denominator= "<<d;
}
}

Compiled By: Ranjan Adhikari, Mohan Bhandari


Standard Template Library
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data
structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms and iterators. It
is a generalized library and so, its components are parameterized.

STL has three components


 Algorithms
 Containers
 Iterators

Algorithms
The header algorithm defines a collection of functions especially designed to be used on ranges of elements.They act
on containers and provide means for various operations for the contents of the containers.
 Algorithm
 Sorting
 Searching
 Important STL Algorithms
 Useful Array algorithms
 Partition Operations

Containers
Containers or container classes store objects and data. There are in total seven standard “first-class” container
classes and three container adaptor classes and only seven header files that provide access to these containers or
container adaptors.
 Sequence Containers: implement data structures which can be accessed in a sequential manner.
 vector
 list
 deque
 arrays
 forward_list
 Container Adaptors : provide a different interface for sequential containers.
 queue
 priority_queue
 stack
 Associative Containers : implement sorted data structures that can be quickly searched
 set
 multiset
 map
 multimap

Iterators

As the name suggests, iterators are used for working upon a sequence of values. They are the major feature that allow
generality in STL.

Compiled By: Ranjan Adhikari, Mohan Bhandari


Compiled By: Ranjan Adhikari, Mohan Bhandari
Chapter 7
Object Oriented Design

Reusability Implies Non-interference


• Conventional programming proceeds largely by doing something to something else, modifying a
record or updating an array, for example. Thus, one portion of code in a software system is often
intimately tied, by control and data connections, to many other sections of the system. Such
dependencies can come about through the use of global variables, through use of pointer values,
or simply through inappropriate use of and dependence on implementation details of other
portions of code. A responsibility-driven design attempts to cut these links, or at least make them
as unobtrusive as possible.
• One of the major benefits of object-oriented programming occurs when software subsystems are
reused from one project to the next. This ability to reuse code implies that the software can have
almost no domain-specific components; it must totally delegate responsibility for domain-specific
behaviour to application- specific portions of the system. The ability to create such reusable code
is not one that is easily learned it requires experience, careful examination of case studies
(paradigms, in the original sense of the word), and use of a programming language in which such
delegation is natural and easy to express.

Programming in small
Programming in the small characterizes projects with the following attributes:
• Code is developed by a single programmer, or perhaps by a very small collection of
programmers. A single individual can understand all aspects of a project, from top to bottom,
beginning to end.
• The major problem in the software development process is the design and development of
algorithms for dealing with the problem at hand.
Programming in large
Programming in the large characterizes software projects with features such as the following:
• The software system is developed by a large team, often consisting of people with many different
skills. No single individual can be considered responsible for the entire project, or even
necessarily understands all aspects of the project.
• With programming in the large, coding managers place emphasis on partitioning work
into modules with precisely-specified interactions. This requires careful planning and careful
documentation.
• The major problem in the software development process is the management of details and the
communication of information between diverse portions of the project.

Role of behaviors in OOP


• Earlier software development methodologies looked at the basic data structures or the overall
structure of function calls, often within the creation of a formal specification of the desired
application. But structural elements of the application can be identified only after a considerable
amount of problem analysis.
• A formal specification often ended up as a document understood by neither programmer nor
client. But behaviour is something that can be described almost from the moment an idea is

Compiled By: Mohan Bhandari, Ranjan Adhikari


conceived, and (often unlike a formal specification) can be described in terms meaningful to both
the programmers and the client.

Responsibility Driven Design


Responsibility-Driven Design (RDD), developed by Rebecca Wirfs-Brock, is an object-oriented
design technique that is driven by an emphasis on behaviors at all levels of development.
Responsibility-Driven-Design is a way of designing complex software systems using objects and
component technology. Responsibility-Driven Design was conceived in 1990 as a shift from
thinking about objects as data + algorithms, to thinking about objects as roles + responsibilities.
Responsibility-Driven Design catalyzes object technology with practical techniques and thinking
tools.

A case study in RDD


 The Interactive Intelligent Kitchen Helper (IIKH) is a PC-based application that will replace the
index-card system of recipes found in the average kitchen. But more than simply maintaining a
database of recipes, the kitchen helper assists in the planning of meals for an extended period, say
a week. The browse the database of recipes, and interactively create a series of menus. The IIKH
will automatically scale the recipes to any number of servings and will print out menus for the
entire week, for a particular day, or for a particular meal. And it will print an integrated grocery
list of all the items needed for the recipes for the entire period.
CRC cards (class responsibility collaborator)
• As the design team walks through the various scenarios they have created, they identify the
components that will be performing certain tasks. Every activity that must take place is identified
and assigned to some component as a responsibility.

i) Give Components a Physical Representation:


While working through scenarios, it is useful to assign CRC cards to different members of
the design team. The member holding the card representing a component records the
responsibilities of the associated software component, and acts as the “surrogate” for the
software during the scenario simulation.
The physical separation of the cards encourages an intuitive understanding of the
importance of the logical separation of the various components, helping to emphasize the
cohesion and coupling
ii) The What/Who Cycle
Design often this proceeds as a cycle of what/who questions. First, the design team
identifies what activity needs to be performed next. This is immediately followed by
answering the question of who performs the action. In this manner, designing a software
system is much like organizing a collection of people, such as a club. Any activity that is
to be performed must be assigned as a responsibility to some component
The secret to good object-oriented design is to first establish an agent for each action.
iii) Documentation
Two documents should be essential parts of any software system: the user manual and the
system design documentation. Work on both of these can commence even before the first
line of code has been written. CRC cards are one aspect of the design documentation, but
many other important decisions are not rejected in them. Arguments for and against any

Compiled By: Mohan Bhandari, Ranjan Adhikari


major design alternatives should be recorded, as well as factors that influenced the final
decisions.

Classname
Responsibilities Collaborators

Fig: CRC card format

Greeter
Display informative initial message Database manager
Offer user choice of options Recipe manager
Pass control to either
• Recipe database manager
• Plan manager for processing

Fig: Greeter class in IIKH scenario

ATM CRC card example

Card reader
Tell ATM when card is inserted ATM
Read information from card Card
Eject card
Retain card

Cash dispenser
 Keep track of cash on hand, starting with Log
initial amount
 Report whether enough cash is available
 Dispense cash

Advantages

• Uses index cards.


– Cheap, readily available, amenable to group use.

Compiled By: Mohan Bhandari, Ranjan Adhikari


• Forces you to be concise and clear.
– Puts your attention on the what, not how.
• Simple, easy methodology
• Intuitive
• Portable

Sequence Diagram

It is used to show dynamic behavior of the components.


• In the diagram, time moves forward from the top to the bottom. Each component is represented
by a labelled vertical line. A component sending a message to another component is represented
by a horizontal arrow from one line to another. Similarly, a component returning control and
perhaps a result value back to the caller is represented. The commentary on the right side of the
figure explains more fully the interaction taking place.

Fig: a sequence diagram for IIKH

Software components
• In programming and engineering disciplines, a component is an identifiable part of a larger
program or construction. Usually, a component provides a particular function or group of related
functions. In programming design, a system is divided into components that in turn are made up
of modules. Component test means testing all related modules that form a component as a group
to make sure they work together.

Compiled By: Mohan Bhandari, Ranjan Adhikari


• In object-oriented programming , a component is a reusable program building block that can be
combined with other components to form an application. Examples of a component include: a
single button in a graphical user interface, a small interest calculator, an interface to a database
manager.

i) Behavior and State: One way to view a component is as a pair consisting of behaviour and state:

• The behavior of a component is the set of actions it can perform. The complete description of all
the behavior for a component is sometimes called the protocol. For the Recipe component this
includes activities such as editing the preparation instructions, displaying the recipe on a terminal
screen, or printing a copy of the recipe.
• The state of a component represents all the information held within it at a given point of time. For
our Recipe component the state includes the ingredients and preparation instructions. Notice that
the state is not static and can change over time. For example, by editing a recipe (a behavior) the
user can make changes to the preparation instructions (part of the state).
ii) Coupling and Cohesion
• Two important concepts in the design of software components are coupling and cohesion.
Cohesion is the degree to which the responsibilities of a single component form a meaningful
unit. High cohesion is achieved by associating in a single component tasks that are related in
some manner. Probably the most frequent way in which tasks are related is through the necessity
to access a common data value. This is the overriding theme that joins, for example, the various
responsibilities of the Recipe component.
• Coupling, on the other hand, describes the relationship between software components. In general,
it is desirable to reduce the amount of coupling as much as possible, since connections between
software components inhibit ease of development, modification, or reuse
iii) Interface and Implementation
It is very important to know the difference between interface and implementation. For example,
when a driver drives the car, he uses the steering to turn the car. The purpose of the steering is
known very well to the driver, but the driver need not to know the internal mechanisms of
different joints and links of various components connected to the steering.
An interface is the user’s view of what can be done with an entity. It tells the user what can be
performed. Implementation takes care of the internal operations of an interface that need not be
known to
the user. The implementation concentrates on how an entity works internally. Their comparison is
shown in Table

Comparison of interface and implementation


Interface Implementation
• It is user’s viewpoint. (What part) • It is developer’s viewpoint. (How part)
• It is used to interact with the outside • It describes how the delegated
world. responsibility is carried out.
• User is permitted to access the • It describes how the delegated
interfaces only. responsibility is carried out.
• It encapsulates the knowledge about the • It provides the restriction of access to
object. data by the user.

Compiled By: Mohan Bhandari, Ranjan Adhikari


.
Formalizing the Interface

• The first step in this process is to formalize the patterns and channels of communication.

• A decision should be made as to the general structure that will be used to implement each
component. A component with only one behavior and no internal state may be made into a
function. Components with many tasks are probably more easily implemented as classes. Names
are given to each of the responsibilities identified on the CRC card for each component, and these
will eventually be mapped onto method names. Along with the names, the types of any arguments
to be passed to the function are identified.

• Next, the information maintained within the component itself should be described. All
information must be accounted for. If a component requires some data to perform a specific task,
the source of the data, either through argument or global value, or maintained internally by the
component, must be clearly identified.

Coming up with names

• Names should be internally consistent, meaningful, preferably short, and evocative in the context
of the problem.

The following general guidelines have been suggested:

• Use pronounceable names. As a rule of thumb, if you cannot read a name out loud, it is not a good
one.
• Use capitalization (or underscores) to mark the beginning of a new word within a name, such as
“CardReader” or “Card reader”, rather than the less readable “cardreader”.
• Examine abbreviations carefully. An abbreviation that is clear to one person may be confusing to
the next. Is a “TermProcess" a terminal process, something that terminates processes, or a process
associated with a terminal?
• Avoid names with several interpretations.

Design and representation of components

 The task now is to transform the description of a component into a software system
implementation major portion of this process is designing the data structures that will be used by
each subsystem to maintain the state information required to fulfil the assigned responsibilities

 It is here that the classic data structures of computer science come into play. The selection of data
structures is an important task, central to the software design process. Once they have been
chosen, the code used by a component in the fulfilment of a responsibility is often almost self-

Compiled By: Mohan Bhandari, Ranjan Adhikari


evident. But data structures must be carefully matched to the task at hand. A wrong choice can
result in complex and inefficient programs, while an intelligent choice can result in just the
opposite.

 It is also at this point that descriptions of behavior must be transformed into algorithms. These
descriptions should then be matched against the expectations of each component listed as a
collaborator, to ensure that expectations are fullled and necessary data items are available to carry
out each process.

Implementation of components
• The next step is to implement each component's desired behavior. If the previous steps were
correctly addressed, each responsibility or behavior will be characterized by a short description.
The task at this step is to implement the desired activities in a computer language.
• An important part of analysis and coding at this point is characterizing and documenting the
necessary preconditions a software component requires to complete a task, and verifying that the
software component will perform correctly when presented with legal input values.
Integration of components
• Once software subsystems have been individually designed and tested, they can be integrated into
the final product. This is often not a single step, but part of a larger process. Starting from a
simple base, elements are slowly added to the system and tested, using stubs: simple dummy
routines with no behavior or with very limited behavior: for the as yet unimplemented parts.
• Testing of an individual component is often referred to as unit testing.
• Integration testing can be performed until it appears that the system is working as desired.
• Re-executing previously developed test cases following a change to a software component is
sometimes referred to as regression testing.
• Give example of car making with different components bumper, gear, engine etc.

Compiled By: Mohan Bhandari, Ranjan Adhikari

You might also like