Sie sind auf Seite 1von 42

II YEAR / IV SEMESTER

(ELECTRICAL AND ELECTRONICS ENGINEERING)


CS6456 - OBJECT ORIENTED PROGRAMMING
UNIT - III
ADVANCED PROGRAMMING

COMPILED BY
M.KARTHIKEYAN, M.E., (AP/IT)
VERIFIED BY

HOD

PRINCIPAL

CORRESPONDENT

DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING


SENGUNTHAR COLLEGE OF ENGINEERING TIRUCHENGODE
1

UNIT III
ADVANCED PROGRAMMING

Templates
Generic Programming
STL
Inheritance
Exceptions
OOP Using C++

LIST OF IMPORTANT QUESTIONS


UNIT III
ADVANCED PROGRAMMING
2

PART-A
1. What is meant by exception? [M/J2016] [A/M2015] [M/J2014] [M/J2012] [or]
Mention the use of exception. [M/J2013]
2. What is a template? [A/M2015] [M/J2012]
3. What is class template? [M/J2014]
4. Define Inheritance. [M/J2013] [or] What is the use of inheritance? [N/D2014]
[N/D2013]
5. List the functions of Standard Template Library. [N/D2014]
6. Mention the advantages of using template functions and template classes.
[Nov/Dec-2012]
7. What is generic function (or) template function?
8. Write down the syntax for try block. [N/D2011]
9. Write the syntax for a function to catch all types of exceptions. [N/D2013]
10. Mention the advantages of using template functions and template classes.
[N/D2012]
11. What is generic programming? [M/J 2016]
PART-B
1. What is a function template? Write a template function to sort array of float and int
using bubble sort. (16m)[A/M2015] (16m)[M/J2012] (10m)[N/D2011] (8m) [N/D2012]
[or] What is a function template? Write a template function for finding the largest number
in a given array. The array parameter must be generic-data types. (16m)[M/J2014]
2. What is inheritance? List out the advantages of Inheritance.[M/J 2016] [7m] Write a
C++ program to implement multiple inheritance [M/J 2016][9m] Discuss the various
types of inheritance that are available in C++ with neat diagram. (16m)[A/M2015] (16m)
[M/J2013] (8m)[A/M2011]

(16m)[N/D2011] (16m)[N/D2012] [or] Explain the different

forms of Inheritance with an example. (16m) [N/D2014]


3. Discuss about exception and its advantages. [M/J2016] [5m].Explain the exception
handling model of C++ with various constructs supported by it. (16m)[M/J2014] (16m)
3

[M/J2013] (6m)[N/D2011] [or] Describe the different types of Exception. Write a


program for Array out of bound exception. (8m)[N/D2014] [or] Discuss in detail about
exception handling constructs and write a program to illustrate divide by zero exception.
(16m)[M/J2012]
4. Explain the Template and Class Template with an example program. (8m) [N/D2014]
(16m)[N/D2013]
5. Explain Overloading of Template functions.
6. What is virtual base class? Create a situation where you will use virtual base class
[M/J2007]
7. Write a C++ program to generate an exception whenever userinput is even number
less than 100.

NOTES
UNIT III
ADVANCED PROGRAMMING

PART A
1. What is meant by exception? [M/J2016] [A/M2015] [M/J2014] [M/J2012] [or]
Mention the use of exception. [M/J2013]
Exceptions are run time anomalies or unused conditions that a program may
encounter while executing. These anomalies can be division by zero, access to an array
outside of its bounds or running out of memory or disk space. The mechanism for
exception handling is,
1. Find the problem (hit the exception).
2. Inform that an error has occurred (throw the exception).
3. Receive the error information (Catch the exception).
4. Take corrective actions (Handle the exception).
2. What is a template? [A/M2015] [M/J2012]
Template enables us to define generic classes and function thus provides
support for generic programming. A template can be used to create a family of classes
or functions. For ex, a class template for an array class would enable us to create
arrays of various data types such as int array and float array.
3. What is class template? [M/J2014]
A class template is also known as a generic class, defines a group or a family of
classes having the same class definition but handling different type of data. While using
class templates, only one class definition needs to be created and the compiler
automatically generates the required classes for handling the individual data types.
4. Define Inheritance. [M/J2013] [or] What is the use of inheritance? [N/D2014]
[N/D2013]
5

Inheritance is the process by which objects of one class acquire the properties of
objects of another class. It supports the concept of hierarchical classification and
supports for reusability. The class which is inherited is known as the base or super
class and class which is newly derived is known as the derived or sub class.
5. List the functions of Standard Template Library. [N/D2014]
The STL provides a ready-made set of common classes for C++, such as
containers and associative arrays, that can be used with any built-in type and with any
user-defined type that supports some elementary operations (such as copying and
assignment). STL algorithms are independent of containers, which significantly reduces
the complexity of the library.
6. Mention the advantages of using template functions and template classes.
[Nov/Dec-2012]

The creation of reusable code.


We can create frameworks that can be applied over and over again to a variety

of programming situations.
Generic programming is achieved by using template.

7. What is generic function (or) template function?


A generic function defines a general set of operations that will be applied to
various types of data. The type of data that function will operate upon is passed to it
as a parameter, a generic function is created using the keyword template.
The general form of a template function definition is:
Template <class T type>ret_type func_name (parameter_list)
{
// body of function
}

Here T type is a placeholder name for a data type used by the function. This name
may be used within the function definition.
8. Write down the syntax for try block. [N/D2011]
The general form is as follows:

9. Write the syntax for a function to catch all types of exceptions. [N/D2013]

10. Mention the advantages of using template functions and template classes.
[N/D2012]

Template is one of the added features in C++. In general itt enables us to define
generic classes and function thus provides support for generic programming. A template
can be used to create a family of classes or functions. For ex, a class template for an
array class would enable us to create arrays of various data types such as int array and
float array.
11. What is generic programming?[M/J 2016]
Generic programming is an approach of writing programs in which a generic type
is passed as a parameter in the definition of a function or a class sothat they can work
with different types of data.
12. What is the significance of Iterators? [N/D'2014]
Iterators are central to generic programming because they are an interface
between containers and algorithms: algorithms typically take iterators as arguments.
Iterators provide a means for accessing data stored in container classes such a vector,
map, list, etc.
13. What is the difference between a class template and an ordinary class?
Class Template
Ordinary Class
A class template define s a group or a The object with same data structure
family of classes having the same and behaviour are grouped into a
class definition but handling different class
type of data.
Syntax:

Syntax:

template<class T>

Class classname

class classname

//Body of the class


//Body of the class

};

};
14. Define STL and write its types.

STL (standard template library) a key problem in programming is programmer


productivity. An important technique is code reuse. STL supports generic programming
which is a critical methodology for enhancing code reuse. Generic programming is
about code that can be used over a wide category of types. The STL contains several
kinds of entities. The three most important are containers, algorithms, and Iterators
15. What are the advantages of inheritance?

Reusability: Inheritance helps the code to be reused in many situations. The


base class is defined and once it is compiled, it need not be reworked. Using the
concept of inheritance, the programmer can create as many derived classes from
the base class as needed while adding specific features to each derived class as

needed.
Saves Time and Effort: The above concept of reusability achieved by
inheritance saves the programmer time and effort. Since the main code written
can be reused in various situations as needed.

16. What are the types of inheritance?

Single inheritance
Multiple inheritance
Hierarchical inheritance
Multiple inheritance
Hybrid inheritance

17. Define virtual base class


The form of inheritance which derives a new class by multiple inheritances of
base classes, which are derived earlier from the same base class is known as multipath
inheritance or virtual base class.
18. What is abstract class [M/J2007]
An abstract class is a class that is designed to be specifically used as a base
class. An abstract class contains at least one pure virtual function. You declare a pure
virtual function by using a pure spiffier (= 0) in the declaration of a virtual member
function in the class declaration.
9

The following is an example of an abstract class:


class AB
{
public:
virtual void f () = 0;
};
PART - B
1. What is a function template? Write a template function to sort array of float and
int using bubble sort. (16m)[A/M2015] (16m)[M/J2012] (10m)[N/D2011] (8m)
[N/D2012] [or] What is a function template? Write a template function for finding
the largest number in a given array. The array parameter must be generic-data
types. (16m)[M/J2014]
Template
Template is one of the added features in C++. It enables us to define generic
classes and function thus provides support for generic programming. A template can be
used to create a family of classes or functions. For ex, a class template for an array
class would enable us to create arrays of various data types such as int array and float
array.
Function template
Like class template, we can also define function templates that could be create a
family of functions of with different argument types.
The general form is,
Template<class T>
Return-type function name (arg of type T)
{
//class member specification with anonymous type T
};
Example 1

Example 2

template<class T>
void swap(T &x,T &y)

template<class T>
void bubble(T a[], int n)
10

{
T temp =x;
x=y;
y=temp;
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"Enter two int values:\n";
cin>>a>>b;
cout<<"Before swap:\n";
cout<<a<<"\t"<<b;
swap(a,b);
cout<<"\nAfter swap:\n";
cout<<a<<"\t"<<b;
cout<<"\nEnter two float values:\n";
cin>>c>>d;
cout<<"\nBefore swap:\n";
cout<<c<<"\t"<<d;
swap(c,d);
cout<<"\nAfter swap:\n";
cout<<c<<"\t"<<d;
getch();
}
The function template swap (T &x, T &y),
we no need to redefine for any other datatype values.

for (int i=0;i<=n-1;i++)


{
for (int j=n-1;i<j;j--)
if(a[j]<a[j-1]
{
swap(a[j],a[j-1]);
}}

}
template<class x>
void swap(X &a, X &b)
{
X temp = a;
a=b;
b=temp;
}
int main()
{
int x[5] = {10,50,30,40,20};
Float y[5] = {1.1,5.5,3.3,4.2,2.2};
bubble(x,5);
bubble(y,5);
cout<<sorted x array:;
for(int i=0;i<5;i++)
cout<<x[i]<<;
cout<<endl;
cout<<sorted y array:;
for(int j=0;j<5;j++)
cout<<y[j]<<;
cout<<endl
return(0);
}
Output:
sorted x array: 10 20 30 40 50
sorted y array: 1.1 2.2 3.3 4.4 5.5

Function Template with multiple parameters


Like template classes, we can use more than one generic data type in the
template statement. The general format is,
template <class T1,class T2,,class Tn>
return-type funname(atg of type T1,T2..)
{
11


};
Example,
template<class T1,class T2>
void disp(T1 x, T2 y)
{
cout<<x<<y;
}
Void main()
{
disp(10,22.2);
disp(F,22);
disp(G,10.23);
}
2. What is inheritance? List out the advantages of Inheritance. [M/J 2016] [7m]
Write a C++ program to implement multiple inheritance [M/J 2016][9m] Discuss
the various types of inheritance that are available in C++ with neat diagram. (16m)
[A/M2015] (16m)[M/J2013] (8m)[A/M2011] (16m)[N/D2011] (16m)[N/D2012] [or]
Explain the different forms of Inheritance with an example. (16m) [N/D2014]
Inheritance
The mechanism of deriving a new class from an old one is called inheritance.
The old is referred to as the base class and the new one is called derived class or sub
class. C++ strongly supports the concept of reusability by means of inheritance. Once a
class has been written and tested. It can be adapted by other programmers to suit their
requirements.
Advantages of Inheritance:
It allows the code to be reused as many times as needed.
The base class once defined and once it is compiled, it need not be reworked.
12

Saves time and effort as the main code need not be written again.
Types of Inheritance

Single inheritance - a derive class with only one base class

Multilevel Inheritance - deriving a class from another derived class

Multiple Inheritance - derive a class from more than one base class

Hierarchical Inheritance - a base class can have more than one derived class

Hybrid Inheritance - combination of more than one type of inheritance

Defining derived classes


The general form of deriving a new class is shown below,
class derived-classname : visibility-mode base-classname
{
Members of derived class;

..
}
The colon indicates that the derived class name is derived from the base class name.
The visibility mode is either private or public. The default visibility mode is private.
Example
Class ABC
{

};
Class XYZ : public ABC // public derived class
{..
}
Class ZXC: private ABC
{
..
};
Class XYZ is public derived class; we can derive another class from XYZ.
13

Class ZXC is private derived class; we cannot derive any more class from ZXC.
When a base class is privately inherited by a derived class, public members of
the base class become private member of the derived class and therefore the public
members of the base class can access only by the member function of the derived
class. They are inaccessible to objects of the derived class. Remember that public
members of a class can be accessed by dot operator. The result is that no public
member of the base class is accessible to the objects of the derived class.
When a base class is publicly inherited by a derived class, public members of
the base class become public members of the derived class and therefore they are
accessible to the objects of the derived class.
Example
class base
{
int a;
public:
int b;
int get()
{
cout<<"\nEnter two numbers:";
cin>>a>>b;
return a;
}
void put()
{
cout<<"\nBase class\n";
cout<<a<<"\t"<<b;
}
};
class derived:public base
{
int c;
public:
void add()
{
c=b+get(); // can access the public
member of class base
}

void dis()
{
cout<<"\nDerived Class";
cout<<"\nThe result is:"<<c;
}
};
void main()
{
clrscr();
base ob;
derived ob1;
ob1.add(); // can access the public
member of class derived
ob1.put();
// can access the public
member of class base
ob1.dis();
// can access the public
member of class derived
getch();
}

14

Visibility of inherited members


Base
visibility
Private
Public
Protected

class

Derived class visibility


Public
Private

Protected

derivation
Not inherited
Public
Public

derivation
Not inherited
Protected
Protected

derivation
Not inherited
Private
Private

1. Single Inheritance
This type of inheritance uses only one base class and only one derived class.
Further, the derived class cannot act as base class.

In the given program, the base class is student and the derived class is
my_Information. Base class contains Student_ID, Name, and Contact_No as its public
data members and a constructor to initialize these members. The derived class contains
print_details() as its public member function.
Example
class Student
{
public:
int student_ID;
char name[15];
int contact_no;
public:
Student()
{
student_ID=1;
strcpy(name,"YOUR NAME");
contact_no=4288;
}
};
2. Multi level inheritance

class my_Information: public Student


{
public:
void print_details()
{
cout<< "ID : "<<student_ID<<endl<<
"Name: "<<name<<endl<< "Contact
Number: "<<contact_no;
}
};
void main()
{ my_Information S1;
clrscr();
S1.print_details();
getch();
}

15

The procedure of deriving a class from another derived class is named as


multilevel inheritance. Best example for multilevel inheritance is son derived from father
which in turn is derived from grandfather.

Example,
class grandparent
{ protected:
char name[20];
grandparent()
{ strcpy(name,"grandparent_name");
}
void disp()
{
cout<<"\n Grandparent Name: "<<name;
}
};
class parent: public grandparent
{ protected:
int age;
public:
parent()
{
strcpy(name,"parent_name");
age=45;
}
void display()
{
cout<<"\n Parent Name: <<name<<"\tAge:
"<<age;
} };

class child: public parent


{
public:
child()
{ strcpy(name,"Your_Name");
age=20;
}
void print_details()
{
disp();
cout<<endl;
display();
cout<<"\n";
cout<<endl<<"Name: "<<name<<"\tAge:
"<<age;
}
};
void main()
{
child c;
clrscr();
c.print_details();
getch();
}

3. Multiple Inheritance
16

When a class is derived from more than one class, then this type of inheritance is
called as Multiple Inheritance. Properties of various base classes are transferred to
single derived class.

The syntax of the derived class with multiple base classes is as follows:
Class D: visibility B1, visibility B2, visibility B3
{
Body of D
};
Example,
class M
{ protected:
int m;
public:
void get_m(int);
};
class N
{ protected:
int n;
public:
void get_n(int);
};
class P:public M, public N
{
public:
void display();
};

void M::get_m(int a)
{ m=a;
}
void N::get_n(int b)
{ n=b;
}
void P::display()
{ cout<<"\n m= "<<m;
cout<<endl<<" n= "<<n;
cout<<endl<<" m*n="<<m*n;
}
void main()
{ P p1;
clrscr();
p1.get_m(10);
p1.get_n(20);
p1.display();
getch();
}

Ambiguity resolution in Inheritance

17

Occasionally, we may face the problem in using the multiple inheritance, when a
function with the same name appears in more than one base class.
Example,
class M
{
public:
void disp()
{
cout<<"\nClass M";
}
};
class N
{
public:
void disp()
{
cout<<"\nClass N";
}
};

class P:public M,public N


{
public:
void display()
{
M::disp();
N::disp();
cout<<"\nClass P";
}
};
void main()
{
clrscr();
P ob;
ob.display();
getch();
}

The statement M::disp() and N::disp() will resolve the ambiguity in multiple inheritance.
In single inheritance also this ambiguity will arise, it can be solve, the following
example shows,
class A
{
public:
void disp()
{
cout<<"\nClass A";
}
};
class B:public A
{
public:
void disp()
{
4. Hierarchical inheritance

cout<<"\nClass B";
}
};
void main()
{
clrscr();
B ob;
ob.disp(); // call the function in derived class B
ob.A::disp(); //Call the function in base class A
getch();
}

18

A single base class can be shared by several derived classes and this type of
inheritance is called as Hierarchical Inheritance. Hierarchical unit shows top down style
through splitting a compound class into several simple sub classes.

Example,
class green: public blue, public yellow
{
public:
green()
{
cout<<" =Green ";
}
};
class violet: public red, public blue
{
public:
violet()
{
cout<<" =Violet ";
}
};
class reddishbrown:public orange, public
violet
{
public:
reddishbrown()
{
cout<<" =Reddish Brown ";
}
};
5. Hybrid inheritance

class yellowishbrown: public green, public


orange
{
public:
yellowishbrown()
{
cout<<" =Yellowish Brown ";
}
};
class bluishbrown: public violet, public
green
{
public:
bluishbrown()
{
cout<<" =Bluish Brown ";
}
};
void main()
{ clrscr();
reddishbrown r;
bluishbrown b;
yellowishbrown y;
getch();
}

19

The combination of one or more types of inheritance is known as hybrid inheritance.

Example,
class PLAYER
{
protected:
char name[15];
char gender;
int age;
};
class PHYSIQUE: public PLAYER
{
protected:
float height;
float weight;
};
class LOCATION
{
protected:
char city[10];
char pin[7];
};
class GAME: public PHYSIQUE, public
LOCATION
{
protected:
char game[15];
public:
void getdata()
{
cout<<"enter following information\n";
cout<<"NAME :";
cin>>name;

cout<<"GENDER:";
cin>>gender;
cout <<"AGE:";
cin>>age;
cout<<"HEIGHT:";
cin>>height;
cout<<"WEIGHT:";
cin>>weight;
cout<<"CITY:";
cin>>city;
cout<<"PINCODE:";
cin>>pin;
cout<<"GAME:";
cin>>game;
}
void show()
{
cout<<"\nentered information\n";
cout<<"\nNAME :";
cout<<name;
cout<<"\nGENDER:"; cout<<gender;
cout <<"\nAGE:";
cout<<age;
cout<<"\nHEIGHT:"; cout<<height;
cout<<"\nWEIGHT:"; cout<<weight;
cout<<"\nCITY:";
cout<<city;
cout<<"\nPINCODE:"; cout<<pin;
cout<<"\nGAME:";
cout<<game;
}
};
void main()
{
clrscr();
GAME G;
G.getdata();
G.show();
getch();
}

20

3. Discuss about exception and its advantages. [M/J2016] [5m].Explain the


exception handling model of C++ with various constructs supported by it. (16m)
[M/J2014] (16m)[M/J2013] (6m)[N/D2011] [or] Describe the different types of
Exception. Write a program for Array out of bound exception. (8m)[N/D2014] [or]
Discuss in detail about exception handling constructs and write a program to
illustrate divide by zero exception. (16m)[M/J2012]
Exception handling
Normally, the programs might have bugs. The most common types of bugs are
logic errors and syntactic errors. The logical errors due to poor understanding of the
problem and solution procedure.
The syntactic errors due to the poor understanding of the language itself. Some
peculiar problems other than logic or syntax errors, they are known as exceptions.
Exceptions are runtime anomalies or unusual condition that a program may encounter
while executing.
Anomalies might include conditions such as division by zero, access to an array
outside of its bounds, or running out of memory or disk spaces. When a program
encounters an exceptional condition, it is important that it is identified and dealt with it
effectively. Exceptional handling is an added feature to ANSI C++. Exceptional
handling provides a type safe, integrated approach, for coping with the unusual
predictable problems that arise while executing a program.
Basics of Exceptional Handling
Exceptions are of two kinds, namely, synchronous and synchronous
exceptions. Errors such as out-of-range index and overflow belong to the
synchronous exceptions. The errors that caused by the events beyond the control of
the program are called asynchronous exceptions. The purpose of exception handling
mechanism is to provide means to detect and report an exceptional circumstance so
that appropriate action can be taken. The following tasks have to be done for handling
the exception:

Find the problem (Hit the exception).

Inform that an error has occurred (Throw the exception).


21

Receive the error information (Catch the exception).

Take corrective action (Handle the exception).


The error handling code basically consists of two segments, one to detect errors

and to throw exceptions, and other to catch the exceptions and to take appropriate
action.
Why Exception Handling?
Following are main advantages of exception handling over traditional error handling.
1) Separation of Error Handling code from Normal Code: In traditional error handling
codes, there are always if else conditions to handle errors. These conditions and the
code to handle errors get mixed up with the normal flow. This makes the code less
readable and maintainable. With try catch blocks, the code for error handling becomes
separate from the normal flow.
2) Functions/Methods can handle any exceptions they choose: A function can
throw many exceptions, but may choose to handle some of them. The other exceptions
which are thrown, but not caught can be handled by caller. If the caller chooses not to
catch

them,

then

the

exceptions

are

handled

by

caller

of

the

caller.

In C++, a function can specify the exceptions that it throws using the throw keyword.
The caller of this function must handle the exception in some way (either by specifying it
again or catching it)
3) Grouping of Error Types: In C++, both basic types and objects can be thrown as
exception. We can create a hierarchy of exception objects, group exceptions in
namespaces or classes, categorize them according to types.

Exception handling mechanism

22

C++ exception handling mechanism basically built up on three keywords namely,


try, throw, and catch. The keyword try is used to preface a block of statements which
may generate exceptions. When an exception is detected, it is thrown using throw
statement in the try block. A catch block defined by the keyword catch catches the
exception thrown by the throw statement in the try block and handles it appropriately.
The catch block must immediately follow the try block that throws the exception. The
general form of these two block are as follows:

When the try block throws the exception, the program control leaves the try block
and enters the catch block. Note that the exceptions are thrown in the form of object. If
the type of object thrown matches the arg in catch block, the statement inside the catch
block is executed. If the thrown object not match with the arg in catch block then the

23

program is aborted with the help of abort() function that will invoked by the compiler
automatically.
When no exception is detected and thrown, the control goes to the statement
immediately after the catch block, that is the catch block is skipped.
Example,
void main()
{
int a,b,c;
clrscr();
cin>>a>>b;
c=a-b;
try
{
if(c==0)
{
throw(c);
}
else
cout<<a/b;
}
catch(int i)
{
cout<<"\nException caught");
}
getch();
}
On running the program, when exception is detected the exception is thrown, the
catch block catches the exception and executes the statement inside the catch block. If
no exception is thrown the catch block is skipped and control goes to next to the catch
block.

The following illustrates the function invoked by the try block throwing exception,

24

The general format of the code is


shown below,
type function(Arglist)
{

Throw(object);
}
..
..
Try
{
..
..
Invoke function here;

..
}
Catch(type arg)
{

Handles exception here

Example
void divide(int a,int b)
{
int c;
try
{
if(b==0)
{
throw(b);
}
else
{
c=a/b;
cout<<c;
}
}
catch(int i)
{
cout<<"Exception caught";
}
}
void main()
{ int a,b;
cin>>a>>b;
divide(a,b);
}

25

Throwing mechanism
When an exception that is desired to be handled is detected, it is thrown using
the throw statement in any one of the following:
throw(exception);
throw exception;
throw;
The operand exception may be of any type. When an exception is thrown, it will
be caught by the catch statement associated with the try block.
Catching mechanism
Code for handling exception is included in catch blocks. A catch block looks like a
function definition and is the form,
catch(type arg)
{
Handles the exception;
}

The catch statement catches an exception whose type matches with the type of
catch argument. When it is caught, the code in the catch block is executed.

Due to mismatch, if an exception is not caught, the abnormal program


termination will occur.

It is important to note that the catch block is simply skipped if the catch statement
does not catch an exception.

Multiple catch statements


It is possible that a program segment has more than one condition to throw an
exception. When an exception is thrown, the exception handlers are searched in order
for an appropriate match. After executing the handler, the control goes to the first
statement after the last catch block for that try.
It is possible that arguments of several catch statements match the type of an
exception. In such cases, the first handler that matches the exception is executed. In
such cases, we can associate more than one catch statement with a try block as shown
below,
26

General form is,


.
try
{

throw exception;
..
..
}
Catch(type1 arg)
{

..
..
}
Catch(type2 arg)
{

..
..
}
.

Catch(typeN arg)
{

..
..
}
.

Example,
void find(int a)
{
try
{
if(a==0)
throw(10);
else if(a==10)
throw('A');
else
throw(1.2);
}
catch(int x)
{
cout<<"Integer Exception caught"<<x;
}
catch(char x)
{
cout<<"character Exception caught"<<x;
}
catch(double x)
{
cout<<"Double Exception caught"<<x;
}
}
void main()
{
int a;
cin>>a;
find(a);
}

Catch all exceptions


In some situation we cannot anticipate all possible types of exceptions and
therefore may not be able to design independent catch blocks to catch them. In such
cases, we can force a catch statement to catch all exceptions.
General form is,

Example,
27

void fun(int a)
{
if(a==10)
throw (1);
else if(a==1)
throw(1.2);
else
throw ('A');
}
void main()
{
int a;
cin>>a;
try
{
fun(a);
}
catch(...)
{
cout<<"Exceeption caught";
}
}

Specifying an exception
It is possible to restrict a function to throw only certain specified exceptions. This
is achieved by adding a throw list clause to the function definition. The general form is
shown below,
Type function (arg list) throw (type-list)
{

..
Function body
}
The type-list specifies the type if exception that the function has to throw.
Throwing any other type of exception will cause an abnormal termination of the
28

program. If we wish to prevent a function from throwing any exception, we may do so by


making the type-list empty. That is we must use throw(); empty list in the function
header line.
Example,
void fun(int a) throw (int,char)
{
if(a==10)
throw (1);
else if(a==1)
throw(1.2);
else
throw ('A');
}
void main()
{
int a;
cin>>a;
try
{
fun(a);
}

catch(int x)
{
cout<<x;
}
catch(char x)
{
cout<<x;
}
catch(double x)
{
cout<<x;
}
}

4. Explain the Template and Class Template with an example program. (8m)
[N/D2014] (16m)[N/D2013]
A key problem in programming is programmer productivity. An important
technique is code reuse. Generic programming is a critical methodology for enhancing
code reuse. Generic programming is about code that can be used over a wide category
of types. In C++, there are three different ways to employ generic coding techniques:
void* pointers, templates, and inheritance. This lets us concentrate on C++ templates
and how they are used effectively.
C++ has template functions that can be used to create generic code. Template
functions are written using the keyword template followed by angle brackets. The angle
brackets contain an identifier that is used as a placeholder for an arbitrary type. C++
uses the keyword template to provide parametric polymorphism, which allows the same

29

code to be used with respect to various types, in which the type is a parameter of the
code body. This is a form of generic programming. The syntax of the template class
declaration is prefaced by,
template <class identifier>
This identifier is a template argument that essentially stands for an arbitrary type. This
argument is instantiated in the declarations.
Templates
Template is one of the added features in C++. It enables us to define generic
classes and function thus provides support for generic programming. A template can
be used to create a family of classes or functions. For ex, a class template for an
array class would enable us to create arrays of various data types such as int array and
float array.
A template can be considered as a kind of macro. When a template is defined
with a parameter that would be replaced by a specified at the time of actual use of the
class or function, the templates are sometimes are called as parameterized classes or
functions.
Class templates
A class template is also known as a generic class, defines a group or a family of
classes having the same class definition but handling different type of data. It is a
simple process to create a generic class using the template with an anonymous type.
The general format of a class template is,
Template<class T>
Class classname
{
//class member specification with anonymous type T
};

The class created from a class template is called a template class. The syntax for
defining an object of a template class is:
30

Classname <type> objectname(arglist);


this process of creating a specific class from a class template is called instantiation.
The compiler will perform the error analysis only when on instantiation takes place,
Example 1
template<class T>
class sample
{
T a,b,c;
public:
sample(T x,T y)
{
a=x;
b=y;
c=a+b;
}
void disp()
{
cout<<c<<"\n";
}
};
void main()
{
clrscr();
sample <int> ob(10,20);
// make the class for adding int type of
data
sample
<float>
ob1(11.23,12.27);
//make the class for adding float data
ob.disp();
ob1.disp();
getch();
}

Example 2
Template<class T>
class calculator
{
T a,b;
public:
void getdata(T x,T y)
{
a=x;
b=y;
}
T add()
{
return a+b;
}
T diff()
{ return a-b;
}
T prod()
{ return a*b;
}
T quotient()
{ return a/b;
}
void display()
{
cout<<The two numbers are: << a<<and
<<b;
cout<<Sum : <<add();
cout<<Difference : <<diff();
cout<<Product : <<prod();
cout<<Quotient : <<quotient();
}
};

31

In the above example 1, the template class is sample, in the constructor, we can add
any numeric data type values. No need to redefine the class for adding various data
types. The same template class can be used to add any numeric data type values.
Class template with multiple parameters
We can design the class template with the multiple parameters. The general form is
shown below,
Template<class T1,class T2,..,class Tn>
Class classname
{
//class member specification with anonymous type T
};
The syntax for defining an object of a template class with multiple parameter is:
Classname <type1,type2,typen> objectname(arglist);
Example,
template<class T1,class T2>
class sample
{
T1 a;
T2 b;
public:
sample(T1 x,T2 y)
{
a=x;
b=y;
}
void disp()
{
cout<<a<<"\t"<<b<<"\n";
}
};

void main()
{
clrscr();
sample <int,float> ob(10,20.233);
sample <float,char> ob1(11.2333,'A');
cout<<"for the first type:\n";
ob.disp();
cout<<"for the second type:\n";
ob1.disp();
getch();
}

The statement; template<class T1,class T2>, the class sample can adopt any two
different data type values.

32

sample <int,float> ob(10,20.233); will invoke the constructor, and assigns the value to
the variable a and b respectively.
sample <float,char> ob1(11.2333,'A'); will invoke the constructor, and assigns the value
to the variable a and b respectively.
5. Explain Overloading of Template functions.
A template function may be overloaded either by template functions or ordinary
functions of its name. in such cases, the overloading resolution is accomplished as
follows:

Call an ordinary function that has an exact match.

Call a template function that could be created with an exact match.

Try normal overloading resolution to ordinary functions and call the one that
matches.

An error is generated if no match is found. Note that no automatic conversions are


applied to arguments on the template functions.
Example,
template <class T>
void dis(T x)
{
Cout<< Template display:<<x;
}
Void dis(int x)
{
Cout<<Explicit display:<<x;
}
Void main()
{
dis(100);
dis(12.34);
dis(A);
}

33

Member function templates


When we created a class template, all the member functions were defined as inline
which was not necessary. We could have defined them outside the class as well. But
remember that the member functions of the templates are parameterized by the type
argument and therefore these functions must be defined by the function templates. The
general form is:
Template<class T>
Returntype classname<t> :: funcname(arg)
{

6. What is virtual base class? Create a situation where you will use virtual base
class [M/J2007]
Virtual base class
Consider a situation where all the three kinds of inheritance, namely, multilevel,
multiple and hierarchical inheritance are involved. This is illustrated in the following
figure:

Inheritance by the child as shown in the above figure might pose some problems. All the
public and protected members of grandparent are inherited into child twice, first via
parent 1 and second via parent 2. This means child would have duplicate set of the
members inherited from the grand parent. This introduces ambiguity and it should be
34

avoided. The duplication of the inherited members due to these multiple paths can be
avoided by making the common base class as virtual base class while declaring the
direct or intermediate base classes as shown below,
Class A
{
..
..
};
Class B:public virtual A
{
..
..
};
Class C:virtual public B
{
..
..
};
Class D:public B,public C
{
..
.. / only one copy of A will be inherited
};
Example,

35

class student
{
protected:
int rollno;
public:
void get_rno()
{
cout<<"\nEnter Roll number:";
cin>>rollno;
}
void put_rno()
{
cout<<"\nRoll Number is:"<<rollno;
}
};
class test: virtual public
student
//derived as virtual
{
protected:
int m1,m2;
public:
void get_ma()
{
cout<<"\nEnter Two marks:";
cin>>m1>>m2;
}
void put_ma()
{
cout<<"\nSubject Marks
are:"<<m1<<"\t"<<m2;
}
};
class sports: virtual public
student //derived as virtual
protected:
int spmarks;
public:

void get_sp()
{
cout<<"\nEnter Soprt marks:";
cin>>spmarks;
}
void put_sp()
{
cout<<"\nSport Mark is:"<<spmarks;
}
};
class result: public test, public sports
{
int total;
public:
void tot()
{
total=m1+m2+spmarks;
}
void disp()
{
put_rno();
put_ma();
put_sp();
cout<<"\nThe total is:"<<total;
}
};
void main()
{
result ob;
clrscr();
ob.get_rno();
ob.get_ma();
ob.get_sp();
ob.tot();
ob.disp();
getch();
}

36

Abstract classes
An abstract class is one that is not used to create objects. An abstract class is
designed only to act as a base class (to be inherited by other classes). In the previous
example, the student class is an abstract class since it was not used to create any
objects.
7. What is virtual function? When do you use a pure virtual function? Differentiate
them [M/J2007]
Virtual function
The ability to refer to objects without any regard to their classes that means the
use of a single pointer variable to refer to the objects of different classes. Here we
use the pointer to base class to refer to all the derived objects. When we use the same
function name in both derived and base class, the function in the base class is declared
as virtual preceding the function definition. When a function is made virtual, C++
determines which function has to invoke depends on the objects that is being referred to
base class pointer
The general form is,
Virtual Return-type fn-name(arglist)
{

}
Here the virtual is the keyword, the fn-name should same in both of the base and
derived class as below:
Class base
{

Public:
Virtual void add()
{
..
}
};
Class derived: public base
{

37

Public:
void add()
{
..
}
};
Just define the object for base and derived and pointer object to base class. Just as
below:
Base *ptr;
Base ob;
Derived ob1;
Ptr=&ob;
Ptr->add();
In the above, the base class object is assigned to ptr, ptr->Add() will call the fn in
base class.
Ptr=&ob1;
Ptr->add();
In the above, the derived class object is assigned to ptr, ptr->Add() will call the fn
in derived class.
Rules for Virtual function

The virtual function must be member of some classes.

They cannot be static members.

They are accessed by using the object pointers.

A virtual function can be a friend of another class.

A virtual function in the base class must be defined even though it is not used.

The prototype of the base and derived class version should be identical.

We cannot have virtual constructors, but we have virtual destructors.

If a virtual function is defined in base class, it need not be redefined in the


derived class. In such cases, calls will invoke the base class function.

38

Example,
class base
{
public:
int a;
void disp()
{
cout<<"\nBase class";
}
virtual void show()
{
a=10;
cout<<"\nA="<<a;
}
};
class derived: public base
{
public:
int b;
void disp()
{
cout<<"\nDerived Class";
}
void show()
{
b=20;
cout<<"\nB="<<b;
}
};

void main()
{
clrscr();
base *ptr;
base ob;
derived ob1;
ptr=&ob; //assign the base class object
ptr->disp(); //call the fn in base class
ptr->show(); //call the fn in base class
ptr=&ob1; //assign the derived class object
ptr->disp(); //try to call the fn in derived
class,but it won't because fn is not virtual
ptr->show(); //call the fn in derived class,
because it is virtual fn
getch();
}

Pure virtual functions or abstract class


If we have not defined any object for the base class, and therefore the function in
the base class has been defined empty. Such functions are call as do-nothing
function or pure virtual functions.
The general form is,
Virtual return-type fn-name()=0;

39

This function is call as pure virtual function. A pure virtual function is a function
declared in a base class that has no definitions relative to the base class. In such cases,
all the derived class should define the function or redeclare the function as pure virtual
function.
A class containing pure virtual function cannot be used to declare any objects of
its own. Such classes are call as abstract class. We can achieve the rum time
polymorphism by declaring the pointer object to the base class and assign the address
of the derived classes.
Example,
class base
{
public:
virtual void disp()=0; //pure
function declaration
};
class derived1:public base
{
public:
void disp()
{
cout<<"Derived class1";
}
};
class derived2:public base
{
public:
void disp()
{
cout<<"\nDerived class2";
}
};

void main()
{
virtual

base *ptr;
derived1 ob1;
derived2 ob2;
clrscr();
ptr=&ob1; //assign derive1 object
ptr->disp();
ptr=&ob2; //assign derive2 object
ptr->disp();
getch();
}

40

7. Write a C++ program to generate an exception whenever userinput is even


number less than 100.
#include <iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter an integer: ";
cin>>n;
try
{
if ( n % 2 == 0)
{
cout << n << " is even.";
if (n<100)
{
throw "\t Even number less than 100";
}
}
else
cout << n << " is odd.";
}
catch( const char* msg)
{
cout <<"\t ERROR MESSAGE:"<<msg;
}
return 0;
}
Output:
Enter an integer: 25
25 is odd.
Enter an integer: 80
80 is even. ERROR MESSAGE : Even number less than 100
Enter an integer: 120
120 is even.

41

42

Das könnte Ihnen auch gefallen