December 2010 Master of Computer Application (MCA) – Semester 2 MC0066 – OOPS using C++ – 4 Credits (Book ID: B0681 & B0715) Assignment

Set – 1 (40 Marks)
Answer all Questions Each Question carries FIVE Marks Book ID: B0681 1. Distinguished between procedural language and OOP language. And Explain the key features of OOP. . Difference Between Procedural Language and OOP Language : 1. Procedural language focuses on organizing program statements into procedures or functions. Larger programs were either broken into functions or modules whereas in Object Oriented Programming bundles both data and functions into one unit known as object. 2. One of the main problems with Procedural approach for programming was data being completely forgotten. The emphasis was on the action and the data was only used in the entire process. Whereas in Object Oriented approach overcomes this problem by modeling data and functions together there by allowing only certain functions to access the required data. 3. The procedural languages had limitations of extensibility as there was limited support for creating user defined datatypes and defining how these datatypes will be handled whereas in OOP language provides this flexibility through the concept of class. 4. Another limitation of the procedural languages is that the program model is not closer to real world objects For example, if you want to develop a gaming application of car race, what data would you use and what functions you would require is difficult questions to answer in a procedural approach. In the object oriented approach solves this further by conceptualizing the problem as group of objects which have their own specific data and functionality. In the car game example, we would create several objects such as player, car, traffic signal and so on. Key Features of OOP : Encapsulation : Data and functions are said to be encapsulated in an single entity as object. Data Hiding : The data is said to be hidden thus not allowing accidental modification.

Inheritance : Inheritance is one of the most powerful feature of Object Oriented Programming Languages that allows you to derive a class from an existing class and inherit all the characteristics and behaviour of the parent class. This feature allows easy modification of existing code and also reuse code. The ability to reuse components of a program is an important feature for any programming language.

1

Polymorphism : Polymorphism is the ability of objects belonging to different types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, so this behavior can be implemented at run time (this is called late binding or dynamic binding). Overloading : Operator overloading feature allows users to define how basic operators work with objects. The operator + will be adding two numbers when used with integer variables. However when used with user defined string class, + operator may concatenate two strings. Similarly same functions with same function name can perform different actions depending upon which object calls the function. This feature of C++ where same operators or functions behave differently depending upon what they are operating on is called as polymorphism (Same thing with different forms). Operator overloading is a kind of polymorphism. 2. Describe the theory with programming examples the selection control statements in C++. There are basically two types of control statements in c++ which allows the programmer to modify the regular sequential execution of statements. They are selection and iteration statements. The selection statements allow to choose a set of statements for execution depending on a condition. 1. If statement Syntax : if (expression or condition) { statement 1; statement 2; } else { statement 3; statement 4; } The expression or condition is any expression built using relational operators which either yields true or false condition. If no relational operators are used for comparison, then the expression will be evaluated and zero is taken as false and non zero value is taken as true. If the condition is true, statement1 and statement2 is executed otherwise statement 3 and statement 4 is executed. Else part in the if statement is optional. If there is no else part, then the next statement after the if statement is exceuted, if the condition is false. If there is only one statement to be executed in the if part or in the else part, braces can be omitted. Following example program implements the if statement. // evenodd.cpp # include <iostream.h> # include <conio.h> void main() { int num; cout<<”Please enter a number”<<endl; cin>>num;

2

If ((a>b) && (b>c)) cout<<a<< “ is the largest number”. else cout<<num <<” is a odd number”.If ((num%2) == 0) cout<<num <<” is a even number”. cout<<”Please enter three numbers”. } The above program accepts a number from the user and divides it by 2 and if the remainder (remainder is obtained by modulus operator) is zero.b. else if ((b>a) && (b>c)) cout<<b<< “ is the largest number”. Statement2. Nested If statement If statement can be nested in another if statement to check multiple conditions.h> void main() { int a.( assumption is that all the numbers are unique. cin>>a>>b>>c. otherwise as odd. } The above program accepts three numbers from the user and displays which is the largest number among the three. getch(). 2. We make use of the relational operator == to compare whether remainder is equal to zero or not. If (condition1) { if (condition 2) { statement1.cpp # include <iostream. } } else statement4. else if ((c>a) && (c>b)) cout<<c<< “ is the largest number”. 3 . } else if (condition3) { statement3.c. Example : //Large. it displays the number is even. the program has to be modified if you would like to allow same number twice).

u . } The above program asks the user to enter l. case ‘u’: y++. default: statement4. The position is initialised to 15 and 15 which are x and y coordinates of his position. switch (pos) { case ‘l’: x--. up and down respectively. cin>>pos. default: cout<<”You selected a wrong option”. Switch statement : One alternative to nested if is the switch statement which can be used to increase clarity in case of checking the different values of the same variable and execute statements accordingly. } cout<<“ you are now located at” <<x<<” “<<y. break. right. y=15. int x=15. break. Depending upon the what user 4 . case ‘d’: y--. u for up and d for down” <<endl. r for right. break. Syntax : Switch (variablename) { case value1: statement1. r . break. case value3: statement3. break. break. cout << “ you are currently located at” <<x<<” “<<y<<endl.3. case value2: statement2. case ‘r’: x++. break.h> void main() { char pos. cout>>”please choose the letter to move l for left. } Example : # include<iostream.d for allowing him to move left.

has selected the the x and y co-ordinates are incremented or decremented by one(x++ is same as x=x+1). i < rows1. else large=b. l. If the user types a letter other than l . int columns1 = 1. Write a program in C++ for matrix multiplication. d and enclosed within single quote. } matrixTwo[0][0] = 1. float **matrixTwo = (float**)malloc(rows2 * sizeof(*matrixTwo)). If you had to compare two variables a and b and then depending on which is larger. 5 . u. The above can be done using conditional operator in the following way: large= (a>b) ? a : b . r.h" #include <iostream> #include <stdlib. for(int i = 0. 3.r. int rows2 = 1. you wanted to store that variable in another variable called large. 4. i++) { matrixTwo[i] = (float*)malloc(columns2 * sizeof(float)). i++) { matrixOne[i] = (float*)malloc(columns1 * sizeof(float)). float **matrixOne = (float**)malloc(rows1 * sizeof(*matrixOne)). matrixOne[2][0] = 1. #include "matrixMultiply. matrixOne[1][0] = -1. int columns2 = 3. he gets an error message. int main() { int rows1 = 3. Conditional Operator : Conditional operator (?:) is a handy operator which acts like a shortcut for if else statement. Since the switch variable is a character. for(int i = 0.h> using namespace std. You would do this using if else statement in the following way: if (a>b) large=a. i < rows2. u. } matrixOne[0][0] = 1. d. The program should accept the dimensions of both the matrices to be multiplied and check for compatibility with appropriate messages and give the output.

float **result. result). i++) { result[i] = (float*)malloc(columns2 * sizeof(float)).1. for(int i = 0. int rows2.matrixOne. int cols1.matrixTwo[0][1] = -1.i<rows1.k<rows2. } else{ float tempResult.j<cols2. for(int k=0. int cols2.1. } result[i][j] = tempResult. } void matrixMultiply(int rows1. i < rows1.3.k++) { tempResult += mat1[i][k]*mat2[k][j]. } 6 . } matrixMultiply(3. for (int i=0.j++) { tempResult = 0. float **mat1. float **mat2. float **result) { if( cols1 != rows2 ){ cout << "Can't Multiply These Matricies!". matrixTwo[0][2] = 1. result = (float**)malloc(rows1 * sizeof(*result)).i++) { for(int j=0. return 0.matrixTwo.

It is invoked by the operand which uses it.d2). But it is not invoked using dot operator.} } } 4. the calling operand can be either left or right of the operator like in case of increment and decrement operators. Example : //unary. } int getcount() 7 . the operator should perform only the most obvious function.add(d1. Several operators such as dot operator. Just like member function the operator has a return value and takes arguments. relational and many other operators work with user defined data-types or classes.cpp # include <iostream. To perform addition of two distance objects we used a call d3. --. What do you mean by operator overloading? Illustrate with suitable example for overloading Unary operators. Operator overloading : Operator overloading is an interesting feature of C++ that allows programmers to specify how various arithmetic. Otherwise it will lead to more confusion. In case of overloading of unary operators. However there are several problems with operator overloading which you should be aware of. While defining the operator functionality for the class the keyword operator is used. It helps to use the default operators with the user defined objects for making the code simpler. conditional operator (?:) etc cannot be overloaded. and should not do something else. public: counter() { count=0. If you are overloading + operator for distance class it should add two distance objects. Instead of such statements it would be more clear if we could use statements like d3=d1+d2. and minus (-). Some of the unary operators are ++. Therefore operator overloading should be used for a class where it is required to perform obvious functions with the default operators and there can be no other meaning for the same. This is possible only if we inform compiler about how + operator works with distance class. scope resolution (::) operator.h> class counter { unsigned int count. Operator overloading works similar to any member function of a class. When using operator overloading. Overloading Unary Operators We have seen that unary operators are those operators which work on one operator.

Write C++ program which demonstrate the difference between static and dynamic binding. } void operator ++() { count++. Book ID: B0715 5. 8 . Therefore the operand is sent by default. struct B: A { void f() { cout << "Class B" << endl. void main() { counter c1. } }. this is called dynamic binding. the operator ++ is defined to return void and take no arguments. } In the above example. ++c1.{ return count. Dynamic Binding : You can specify that the compiler match a function call with the correct function definition at run time. The first example demonstrates static binding: #include <iostream> using namespace std. } }. } }. c1++. struct A { void f() { cout << "Class A" << endl. You declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific function The following examples demonstrate the differences between static and dynamic binding. All unary operators do not take no arguments as it operates on only one operand and that operand itself invokes the operator. cout<<c1.getcount().

this can be determined at run time.f(). struct A { virtual void f() { cout << "Class A" << endl. } The following is the output of the above example: Class A When function g() is called. The following example is the same as the previous example. At compile time. void g(A& arg ) { arg.f(). } 9 . However. g(x). function A::f() is called. } }. } }. the compiler knows only that the argument of function g() will be a reference to an object derived from A. struct B: A { void f() { cout << "Class B" << endl. } int main() { B x.void g(A& arg) { arg. g(x). it cannot determine whether the argument will be a reference to an object of type A or type B. } int main() { B x. although the argument refers to an object of type B. except that A::f() is declared with the virtual keyword: #include <iostream> using namespace std.

return 0. int). rect. If we want to declare an external function as friend of a class. but by the type of object that the reference refers to. Friend Functions : Friend Functions are the functions which can have access to the private and protected members of the class. } 10 . we do it by declaring a prototype of this external function within the class.width = rectparam. Describe the Friend functions and friend classes with programming examples. class CRectangle { int width. They can be declared anywhere within a class declaration.area(). but it is common practice to list friends at the beginning of the class.height = rectparam. as the class has no control over the scope of friends.width*2. int b) { width = a. void CRectangle::set_values (int a. return (rectres). }. rectres. cout << rectb. } int main () { CRectangle rect. height = b. rectb.The following is the output of the above example: Class B The virtual keyword indicates to the compiler that it should choose the appropriate definition of f() not by the type of reference. public: void set_values (int. thus allowing this function to have access to the private and protected members of this class. height.height*2. 6.} friend CRectangle duplicate (CRectangle). int area () {return (width * height).set_values (2. rectres. rectb = duplicate (rect). The public and protected keywords do not apply to friend functions.3). } CRectangle duplicate (CRectangle rectparam) { CRectangle rectres. and preceding it with the keyword friend: // friend functions #include <iostream> using namespace std.

. The set member can iterate over the collection and reset each point: 11 . double m_y. Generally. Since the collection class is a friend of CPoint. }. // Point class. m_y(y) { } ~CPoint(void) { } // .. public: CPoint(const double x. For example. so whenever possible it is better to use members of the same class to perform operations with them. public: CPointCollection(const int nSize) : m_vecPoints(nSize) { } ~CPointCollection(void).. From within that function we have been able to access the members width and height of different objects of type CRectangle. void set(const double x. the use of friend functions is out of an object-oriented programming methodology. }. This is useful when individual elements of the collection need to be manipulated. The friend functions can serve. suppose we have a class CPoint that represents a coordinate. which are private members. and a class CPointCollection that holds a list of points. class CPointCollection. a set method of the CPointCollection class could set all CPoint elements to a particular value (vector is a STL container which is discussed in detail in Chapter 8): class CPointCollection { private: vector<CPoint> m_vecPoints. const double y). Friend classes are used in cases where one class is tightly coupled to another class. we could declare CPointCollection as a friend of the CPoint class: // Forward declaration of friend class. Such as in the previous example. // . const double y) : m_x(x).. for example. Since the collection class may need to manipulate point objects. it has access to the internal data of any point object. It isn't! It simply has access to its private and protected members without being a member. private: double m_x. For example. Friend Classes : A class can declare a member function of another class as a friend. to conduct operations between two different classes.The duplicate function is a friend of CRectangle. Notice that neither in the declaration of duplicate() nor in its later use in main() have we considered duplicate a member of class CRectangle. it would have been shorter to integrate duplicate() within the class CRectangle. or declare another class as a friend class. class CPoint { friend CPointCollection.

#include<fstream. 12 . each class must explicitly choose its friends.For reading from or writing to the file. The principle behind this is that friendship is not implicitly granted.h> int main() { char str[2000]. Most of the applications will have their own features to save some data to the local disk and read data from the disk again. Open the file Read the data Close the file This sample code snippet explains how to use the c++ file i/o stream operators to read data from a file. Derived classes of CPointCollection will not be able to access CPoint. Friendship is also not something that is passed down a class hierarchy. i<nElements. the converse is not true.Can be used for both read/write c++ file I/O operations The most important methods which will be used for any file operations are: fstream::open method . Illustrate with suitable examples various file handling methods in C++.m_x = x.Flushes all buffer and close the file Reading a text file using fstream class: There are several ways of reading the text from a file. } } One thing important about friend classes is that friendship is not mutual: although CPointCollection can access CPoint. for(int i=0. fstream::close .size().Can be used for File read/input operations ofstream . C++ File I/O Classes and Functions: There are 3 File I/O classes in C++ which are used for File Read/Write operations.to open the file fstream::Operator >> and fstream::Operator << .Can be used for File write/output operations fstream . i++) { m_vecPoints[i]. m_vecPoints[i]. In all cases the header file fstream.void CPointCollection::set(const double x. const int nElements = m_vecPoints. They are ifstream .m_y = y. const double y) { // Get the number of elements in the collection. C++ File I/O classes simplify such file read/write operations for the programmer by providing easier to use classes.h must be included. File handling is an important part of all programs. 7. But all of them have a common approach as follows. // Set each element.

1. cout <<str.eof()) { file_op. return 0. There are several open modes. each of them with a different purpose.close().close(). Write to a file 3.h> int main() { fstream file_op("c:\\CoderSource_file. file_op.ios::in). return 0. This also follows the same order of operations. file_op.in write mode 2.txt". open a file . close the file Look at the following sample code to see the difference. #include <fstream. while(!file_op. } The class fstream.2000). } Writing to a text file using fstream class: Writing to a text file can also be achieved with the stream operators. which is used above is the one which is commonly used for c++ file i/o manipulations. One is the file path and the second is the File Open mode. cout <<endl. #include <fstream. though with a slight difference.ios::in). Here is the example for using fstream getline method. In order not to miss these characters we can either use fstream::get() or fstream::getline() methods. fstream file_op("c:\\test_file.ios::out).h> int main() { char str[2000]. } file_op.fstream file_op("c:\\test_file. The constructor of fstream takes 2 parameters. The output misses the white spaces and the end of line characters. while(file_op >> str) cout << str . 13 .getline(str.txt". file_op<<"Test Write to file". But if we look at the output closely.txt".close(). there is a draw back in using this stream operator read.

return 0. } Output: stream<T>::f() stream<char>::f() In the above example. template <> class stream<char> { public: void f() { cout << "stream<char>::f()"<< endl. stream<char> sc. This is called template specialization. template <class T> class stream { public: void f() { cout << "stream<T>::f()"<< endl.f(). } To modify the data or to seek to a different position inside the file. The following example defines a template class specialization for template class stream. 8. si. } }. other streams will be handled by the template class generated from the class template 14 . to close the file pointer. stream<char> is used as the definition of streams of chars. These functions can be used to relocate the record insert position to the desired locations. What is template specialization? Describe a scenario in which template class partial specialization is considered appropriate. Class Template Specialization :In some cases it is possible to override the template-generated code by providing special definitions for specific types. sc. } }. the destructor of the fstream class will close the file when the object goes out of scope.f(). int main() { stream<int> si. #include <iostream> using namespace std. This is not mandatory. return 0.. Even if this function is not called by the application. the c++ file i/o class fstream provides member functionslike seekg() etc. After all the C++ File I/O operations we do a fstream::close().

int main() { // generates an instantiation from the base template X<char. //generates an instantiation from the partial specialization X<char. 15 . //partial specialization template<typename T1> class X<T1. typename T2> class X { }. . } A partial specialization matches a given actual template argument list if the template arguments of the partial specialization can be deduced from the actual template argument list. int> xii .Template Class Partial Specialization : You may want to generate a specialization of the class for just one parameter. int> { }. for example //base template class template<typename T1. char> xcc . return 0 .

In the object oriented approach solves this further by conceptualizing the problem as group of objects which have their own specific data and functionality. One of the main problems with Procedural approach for programming was data being completely forgotten. The procedural languages had limitations of extensibility as there was limited support for creating user defined datatypes and defining how these datatypes will be handled whereas in OOP language provides this flexibility through the concept of class. 3. The ability to reuse components of a program is an important feature for any programming language. Another limitation of the procedural languages is that the program model is not closer to real world objects For example. car. And Explain the key features of OOP 1. In the car game example. This feature allows easy modification of existing code and also reuse code. Procedural language focuses on organizing program statements into procedures or functions. Inheritance : Inheritance is one of the most powerful feature of Object Oriented Programming Languages that allows you to derive a class from an existing class and inherit all the characteristics and behaviour of the parent class. The emphasis was on the action and the data was only used in the entire process. Distinguished between procedural language and OOP language. Larger programs were either broken into functions or modules whereas in Object Oriented Programming bundles both data and functions into one unit known as object. we would create several objects such as player.December 2010 Master of Computer Application (MCA) – Semester 2 MC0066 – OOPS using C++ – 4 Credits (Book ID: B0681 & B0715) Assignment Set – 2 (40 Marks) Answer all Questions Each Question carries FIVE Marks Book ID: B0681 1. Key Features of OOP : Encapsulation : Data and functions are said to be encapsulated in an single entity as object. Data Hiding : The data is said to be hidden thus not allowing accidental modification. 16 . if you want to develop a gaming application of car race. what data would you use and what functions you would require is difficult questions to answer in a procedural approach. 2. 4. traffic signal and so on. Whereas in Object Oriented approach overcomes this problem by modeling data and functions together there by allowing only certain functions to access the required data.

void main() { sample obj1. Operator overloading is a kind of polymorphism.cpp # include<iostream. cout<<”Constructor invoked”<<endl. The operator + will be adding two numbers when used with integer variables. } 17 . The following program implements the constructor and destructors for a class // constdest.h> class sample { private: int data. This feature of C++ where same operators or functions behave differently depending upon what they are operating on is called as polymorphism (Same thing with different forms).} }.display(). obj. This feature makes it very useful to initialize the class data members whenever a new object is created. 2. They are invoked automatically whenever the object’s life expires or it is destroyed. Discuss the constructors and Destructors with suitable example Constructors : Constructors are member functions of a class which have same name as the class name. } ~sample() { cout<<”Destructor invoked”. + operator may concatenate two strings. It can be used to return the memory back to the operating system if the memory was dynamically allocated. Destructors : Destructors on the other hand are also member functions with the same name as class but are prefixed with tilde (~) sign to differentiate it from the constructor. Similarly same functions with same function name can perform different actions depending upon which object calls the function. It also can perform any other function that needs to be performed for all the objects of the class without explicitly specifying it. However when used with user defined string class. public: sample() { data=0.Polymorphism and Overloading : Operator overloading feature allows users to define how basic operators work with objects. } void display() { cout<<”Data=”<<data<<endl. Constructors are called automatically whenever an object of the class is created.

Even though the address of derived classes is assigned to the pointer. Describe the theory behind Virtual Functions and Polymorphism along with suitable programming examples for each. However. we get the desired result. You would like to create a pointer that points to any of the derived class objects. Let us suppose you have a class base as shown in the following program and two classes derv1 and derv2 are publicly derived from class base. If you create a pointer of derv1. Compiler will complain if you assign any other object is assigned to the pointer. However. In the following program we have made the base class function show() as virtual function by prefixing with the keyword virtual. class derv2: public base { public: void show() { 18 . When the program ends the object is destroyed which invokes the destructor.If you run the above program you will get the output as follows: Constructor invoked Data=0 Destructor invoked When object of sample class. class derv1:public base { public: void show() { cout<<“derv1”<<endl. } }. constructors can have arguments and can be overloaded so that different constructors can be called depending upon the arguments that is passed. then it can point to derv1 object only.cpp # include <iostream. Virtual functions are primarily used in inheritance. object is created. automatically the constructor is invoked and data is initialized to zero. Virtual Functions : Virtual means existing in effect but not in reality. if the base class function is made virtual. Destructors on the other hand cannot be overloaded and cannot have any arguments. the compiler executes the base class function. } }. 3. //virtual. Please note that both the constructor and destructor is declared as public and they have no return value.h> class base { public: virtual void show() // virtual function { cout<<“base”<<endl. The solution is to create a pointer to Base class.

we now get the output as: derv1 derv2 In the above program. You would like to write a common code as following so that you can draw several of these shapes with same code and the shape to be drawn is decided during runtime: Shape *ptrarr[100] for (int j=0. 4. This is an very desirable capability that completely different functions are executed by same function call. Let us suppose each of the classes has a member function draw() that causes the object to be drawn on the screen. ptr=&dv2. } By declaring the base class function as virtual. a type of polymorphism which allows the same operators to behave differently with different datatypes/operands. circle. base *ptr. This is known as late binding or dynamic binding. It allows reuse of code without modifying the original code. the draw() function must be declared as virtual in the base class (in the shape class). depending on the contents in the pointer. If the ptrarr is pointing to a rectangle. This is exactly what is polymorphism. a rectangle is drawn. } }. . However to implement this approach several conditions should be met. void main() { derv1 dv1. For Example :Let’s us suppose that we want to create a class shape and derive classes such as rectangle. circle is drawn.j++) Ptrarr[j]->draw(). Discuss the types of Inheritance with suitable example for each. Polymorphism : Polymorphism means same content but different forms. Inheritance is a very powerful featu re of object oriented programming. Firstly. In C++. derv2 dv2.j<n. ptr=&dv1. circle. triangle should be derived from a single class (Here it is shape class). ptr->show().cout<<“derv2”<<endl. polymorphism enables the same program code calling different functions of different classes. the compiler decides which class function to call during runtime. ptr->show(). Operator overloading is. It also allows flexibility to programmer to make modifications to the program without altering the original code which saves debugging and programming time and effort. Secondly. all the classes rectangle. If it is point int to circle. triangle etc. 19 .

Let us suppose. which takes a char* as its argument. that function will exit in the process of throwing. there are two classes A and B. and of course the constructor is called for that object.Types Of Inheritance : Hierarchical Inheritance : We can have several classes derived from a single base class like shown below. In such case the grand child class inherits all the properties of child and parent classes. public B { }. Book ID: B0715 5. you want to derive a class C from A and B. The try block : If you’re inside a function and you throw an exception (or a called function throws an exception). Catching an Exception : If a function throws an exception. If you don’t want a throw to leave a function. one where you don’t have enough information in the current context to decide what to do – you can send information about the error into a larger context by creating an object containing that information and “throwing” it out of your current context. The keyword throw causes a number of relatively things to happen. This is called throwing an exception. You can use any type when you throw (including built-in types). Write about the following with the help of suitable programming examples: A) Throwing an Exception B) Catching an Exception Throwing an Exception : If you encounter an exceptional situation in your code – that is. The syntax of class definition will be as follows: class C : public A. Multi Level Inheritance : Inheritance can also be multilevel inheritance where another class is derived from the derived class. it must assume that exception is caught and dealt with. Here’s what it looks like: throw myerror(“something bad happened”). myerror is an ordinary class. but often you’ll use special types created just for throwing exceptions. The try block is an ordinary scope. This is called the try block because you try your various function calls there. The advantages of C++ exception handling is that it allows you to concentrate on the problem you’re actually trying to solve in one place. First it creates an object that isn’t there under normal program execution. even though that object type isn’t normally what the function is designed to return. Then the object is. “returned” from the function. in effect. Multiple Inheritance : Multiple Inheritance is the process of inheriting a class from more than one parent class. preceded by the keyword try: 20 . and then deal with the errors from that code in another place. This is also extensively used in class libraries. This would be required in several instances where you would like to have the functionalities of several classes . The syntax for implementing multiple inheritance is similar to single inheritance. you can set up a special block within the function where you try to solve your actual programming problem (and potentially generate exceptions).

which could presumably be detected before the program executes.try { // Code that may generate exceptions } 6. at some level. the function or try block surrounding the try block that failed to catch the exception. At that point. It is actually pointer to a function and its default value is the Standard C library function abort(). that is. logic_error : Derived from exception. but instead must call some sort of programtermination function.” An uncaught exception also occurs if a new exception is thrown before an existing exception reaches its handler – the most common reason for this is that the constructor for the exception object itself causes a new exception. which can presumably be detected only when the program executes.” and no further searching occurs. Your custom terminate() must take no arguments and have a void return value. Reports runtime errors. any terminate() handler you install must not return or throw an exception. In addition. set_terminate() : You can install your own terminate() function using the standard set_terminate() function. runtime_error : Derived from exception. which returns a pointer to the terminate() function you are replacing. it is “uncaught” or “unhandled. Reports program logic errors. (The location of this higher-context try block is not always obvious at first glance. so you can restore it later if you want. that exception moves to the next-higher context. Functions which can be used for Uncaught Exceptions : terminate() : This is the special function which will be called automatically if an exception is uncaught. Write about the following with the help of suitable programming examples: A) Uncaught Exceptions B) Standard Exceptions Uncaught Exceptions : If none of the exception handlers following a particular try block matches an exception. 21 . Standard Exceptions : The set of exceptions used with the Standard C++ library are also available for your own use. you can derive from it. invalid_argument : Indicates an invalid argument to the function it’s thrown from. domain_error : Reports violations of a precondition. The following are details for some of the standard exceptions: Exception : The base class for all the exceptions thrown by the C++ standard library. Generally it’s easier and faster to start with a standard exception class than to try to define your own. the exception is considered “caught. If no handler at any level catches the exception. a handler matches the exception. which immediately exits the program with no calls to the normal termination functions (which means that destructors for global and static objects might not be called). it means the problem is unrecoverable. If the standard class doesn’t do what you need. You can ask what() and get a result that can be displayed as a character representation. If terminate() is called.) This process continues until.

you still hope to continue execution after the exception is handled. Describe the time overhead of operations on sequence containers Sequence Containers : There are three types of sequence containers to store data in linear sequence. don’t throw an exception. Resumption : It means the exception handler is expected to do something to rectify the situation. Alternatively. it’s one thing to terminate to a handler that’s far away. Whoever threw the exception decided there was no way to salvage the situation. presuming success the second time.length_error : Indicates an attempt to produce an object whose length is greater than or equal to NPOS (the largest representable value of type size_t). call a function that fixes the problem). it seems it isn’t quite so useful in practice. so your exception is more like a function call – which is how you should set up situations in C++ where you want resumption-like behavior (that is. and then use the following table to help in choosing. and then the faulting function is retried. but to jump to that handler and then back again may be too conceptually difficult for large systems where the exception can be generated from many points. deque and list : vector<Type> deque<Type> list<Type> To choose a container. place your try block inside a while loop that keeps reentering the try block until the result is satisfactory. programmers using operating systems that supported resumptive exception handling eventually ended up using termination-like code and skipping resumption. Termination: In termination (which is what C++ supports) you assume the error is so critical there’s no way to get back to where the exception occurred. decide what sort of operations you will most frequently perform on your data. 8. Time overhead of operations on sequence containers Operation Access first Element Access last element Access random element Add/delete at beginning Add/delete at end Add/delete at random Vector constant constant constant linear constant linear Deque constant constant constant constant constant linear List constant constant linear constant constant constant 22 . Write the advantages of using exception handling with its basic models There are two basic models in Exception-Handling theory. If you want resumption. 7. One reason may be the distance that can occur between the exception and its handler. and they don’t want to come back. So although resumption sounds attractive at first. Historically. These are the vector.

They are implemented as double linked lists structures in order to support bidirectional iterators.Each container has attributes suited to particular applications. but it does allow random access to elements using the array like syntax. Insertion and deletion at the end of vector is “cheap” . Memory overhead of a vector is very low and comparable to a normal array. 23 . O(1). Deque : The double ended queue. but as the name suggests you can efficiently insert or delete elements at either end. List : Lists don’t provide access like an array or vector. Deque like vector is not very good at inserting or deleting elements at random positions. but are suited to applications where you want to add or remove elements to or from the middle. has similar properties to a vector. Vector : The vector class is similar to an array and is able to access elements at any position with a constant time overhead .

Sign up to vote on this title
UsefulNot useful