Sie sind auf Seite 1von 26

1 MC0066 OOPS USING C++ Set 1. Q 1. Distinguished between procedural language and OOP language.

And
Explain the key features of OOP. Ans:

Procedural programming creates a step by step program that guides the application through a sequence of instructions. Each instruction is executed in order. Procedural programming also focuses on the idea that all algorithms are executed with functions and data that the programmer has access to and is able to change.

Object-oriented programming (OOP) is a programming paradigm using "objects" data structures consisting of data fields and methods together with their interactions to design applications and computer programs. Programming techniques may include features such as data abstraction,

encapsulation, messaging, modularity, polymorphism, and inheritance.


The focus of procedural programming is to break down a programming task into a collection of variables, data structures, and subroutines, whereas in object-oriented programming it is to break down a programming task into data types (classes) that associate behavior (methods) with data (members or attributes). The most important distinction is whereas procedural programming uses procedures to operate on data structures, object-oriented programming bundles the two together so an "object", which is an instance of a class, operates on its "own" data structure. Nomenclature varies between the two, although they have similar semantics: Procedural Object-Oriented procedure method record object module class Procedure call message

Key features of OOP :

Objects The instances of a class which are used in real functionality its variables and operations. Class Basic building blocks OOP and a single entity which has data and operations on data together. Inheritance- This is the process by which a class can be derived from a base class with all features of base class and some of its own. This increases code reusability.

Moumita Mondal. MCA-2nd sem

2 MC0066 OOPS USING C++


Polymorphism- This is the ability to exist in various forms. For example an operator can be overloaded so as to add two integer numbers and two floats. Encapsulation Encapsulation is capturing data and keeping it safely and securely from outside interfaces. ..

Set 1. Q 2. What is function overloading? Write a c++ program to implement a function


overloaded. Ans:
Function overloading is a feature of C++ that allows us to create multiple functions with the same name, so long as they have different parameters. C++ permits the use of two functions with the same name. However such functions essentially have different argument list. The difference can be in terms of number or type of arguments or both. This process of using two or more functions with the same name but differing in the signature is called function overloading. But overloading of functions with different return types are not allowed. In overloaded functions, the function call determines which function definition will be executed. The biggest advantage of overloading is that it helps us to perform same operations on different data types without having the need to use separate names for each version. Example 1: Overloading Functions that differ in terms of NUMBER OF PARAMETERS //Example Program in C++ #include<iostream.h> //FUNTION PROTOTYPES int func(int i); int func(int i, int j); void main(void) { cout<<func(10);//func(int i)is called cout<<func(10,10);//func(int i, int j) is called } int func(int i) { return i; } int func(int i, int j) { return i+j; }

Example 2: Overloading Functions that differ in terms of TYPE OF PARAMETERS

Moumita Mondal. MCA-2nd sem

3 MC0066 OOPS USING C++


//Example Program in C++ #include<iostream.h> //FUNTION PROTOTYPES int func(int i); double func(double i); void main(void) { cout<<func(10);//func(int i)is called cout<<func(10.201);//func(double i) is called } int func(int i) { return i; } double func(double i) { return i; }

. Set 1. Q 3. Discuss the constructors and Destructors with suitable example.


Ans:
Constructors and destructors are very important components of a class. Constructors are member functions of a class which have same name as the class name. Constructors are called automatically whenever an object of the class is created. This feature makes it very useful to initialize the class data members whenever a new object is created. It also can perform any other function that needs to be performed for all the objects of the class without explicitly specifying it. Purpose: To initialize the private data member of a class. Rules: 1. it is a special type of method of a class name. 2. It has no return type even void. 3. It is automatically invoked when object is created that means it is an implicit call. 4. We can write more than one constructor in one program by using different parameter which is called constructor overloading. It is also an example of polymorphism. 5. We can write the constructor into the public sector of a class. 6. Generally constructors are of three types. (a) Default constructor: constructor with no argument (b) parameterized constructor : constructor with arguments or parameter (C) Copy constructor: constructor passing object as a reference. 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. They are invoked automatically whenever the

Moumita Mondal. MCA-2nd sem

4 MC0066 OOPS USING C++


objects life expires or it is destroyed. It can be used to return the memory back to the operating system if the memory was dynamically allocated.

Destructor is used to de-allocate m/m which is created by constructor It is similar to constructor by precesiding ~ sign. It cannot be overloaded, means in one program we can write only one destructor.

// example on constructors and destructors #include <iostream> using namespace std; class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () { return (*width * *height); } }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () { delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } Output: rect area: 12 rectb area: 30

. Set 1. Q 4. What do you mean by operator overloading? Illustrate with suitable example
for overloading Unary operators.

Moumita Mondal. MCA-2nd sem

5 MC0066 OOPS USING C++

Ans: Operator overloading is an interesting feature of C++ that allows programmers to specify how various arithmetic, relational and many other operators work with user defined datatypes or classes. It provides a flexible way to work with classes and can make program code look obvious. Several operators such as dot operator, scope resolution (::) operator, conditional operator (?:) etc cannot be overloaded. Example: Unary operators act on only one operand. Some commonly used unary operators are unary minus (-), increment (++) and decrement (--) operators. //****This program illustrates the overloading of unary munus ( - ) operator****** #include class Minus { private: int a, b, c ; public: Minus( ) // Default Constructor { } Minus(int A, int B, int C) { a=A; b=B; c=C; } void display(void); //********Declaration of the operator function********** void operator - ( ); }; // End of the Class Definition //***********Member Function Definitions************* inline void Minus :: display(void) { cout << "\t a = " << a << endl ; cout << "\t b = " << b << endl ; cout << "\t c = " << c << endl ; } //*********Definition of the operator function*********** inline void Minus :: operator - ( ) { a = -a ; b = -b ; c = -c ; } //*************Main Function Definition*************** void main(void) { Minus M(5, 10, -15) ; cout << "\n Before activating the operator - ( )\n" ; M.display( ) ; -M ; cout << "\n After activating the operator - ( )\n" ;

Moumita Mondal. MCA-2nd sem

6 MC0066 OOPS USING C++


M.display( ) ; } Output:

..

Set 1. Q 5. Write C++ program which demonstrate the difference between static and
dynamic binding. Ans:
The following example demonstrates the differences between static and dynamic binding. The first example demonstrates static binding: #include<iostream> Using namespace std; Struct A { Void f() { cout<<Class A<<endl; } }; Struct B: A { Voidf() {cout<<Class B<<endl; } }; Void g(A& arg) { Arg.f(); } Int main () { B x; g(x); }

Set 1. Q 6. Difference between a static member function and non-static member


functions with appropriate example.

Moumita Mondal. MCA-2nd sem

7 MC0066 OOPS USING C++

Ans:
We cannot have static and non-static member functions with the same names and the same number and type of arguments. Like static data members, we may access a static member function f() of a class A without using an object of class A. A static member function does not have a this pointer. Example: // static_member_functions.cpp #include <stdio.h> class StaticTest { private: static int x; public: static int count() { return x; } }; int StaticTest::x = 9; int main() { printf_s("%d\n", StaticTest::count()); } Output: 9 Nonstatic member functions have an implied argument, this, that points to the object through which the function is invoked. The type of this is type * const. These functions are considered to have class scope and can use class data and other member functions in the same class scope directly. Example:

#include <iostream> using namespace std; struct X { private: int a; public: void Set_a(int a) { // The 'this' pointer is used to retrieve 'xobj.a' // hidden by the automatic variable 'a' this->a = a; } void Print_a() { cout << "a = " << a << endl; } }; int main() { X xobj; int a = 5; xobj.Set_a(a);

Moumita Mondal. MCA-2nd sem

8 MC0066 OOPS USING C++


xobj.Print_a(); }
..

Set 1. Q 7. Writer C++ program to demonstrate the complete implementation of class


template stack. Ans:
//stack.h #pragma once template <class T> class Stack { public: Stack(int = 10); ~Stack() { delete [] stackPtr; } int push(const T&); int pop(T&); int isEmpty()const { return top == -1; } int isFull() const { return top == size - 1; } private: int size; int top; T* stackPtr; }; //constructor with the default size 10 template <class T> Stack<T>::Stack(int s) { size = s > 0 && s < 1000 ? s : 10; top = -1; // initialize stack stackPtr = new T[size]; } // push an element onto the Stack template <class T> int Stack<T>::push(const T& item) { if (!isFull()) { stackPtr[++top] = item; return 1; // push successful } return 0; // push unsuccessful } // pop an element off the Stack template <class T> // Number of elements on Stack

// pop an element off the stack

Moumita Mondal. MCA-2nd sem

9 MC0066 OOPS USING C++


int Stack<T>::pop(T& popValue) { if (!isEmpty()) { popValue = stackPtr[top--]; return 1; // pop successful } return 0; // pop unsuccessful }

..

Set 1. Q 8. What is template specialization? Describe a scenario in which template class


partial specialization is considered appropriate. Ans:

In some cases it is possible to override the template-generated code by providing special definitions for specific types. This is called template specialization.

//base template class template<typename T1, typename T2> class X { }; //partial specialization template<typename T1> class X<T1, int> { }; int main() { // generates an instantiation from the base template X<char, char> xcc ; //generates an instantiation from the partial specialization X<char, int> xii ; return 0 ; } 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. . .

Set 2. Q 1. Write advantage of multiple inheritances. And write ac++ program to


implement the multiple inheritances. Ans:
We can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance. Multiple Inheritance is the process of inheriting a class from more than one parent class. This would be required in several instances where you would like to have the functionalities of several classes. This is also extensively used in class libraries. Example: #include <string> class Person { private:

Moumita Mondal. MCA-2nd sem

10 MC0066 OOPS USING C++


std::string m_strName; int m_nAge; bool m_bIsMale; public: Person(std::string strName, int nAge, bool bIsMale) : m_strName(strName), m_nAge(nAge), m_bIsMale(bIsMale) { } std::string GetName() { return m_strName; } int GetAge() { return m_nAge; } bool IsMale() { return m_bIsMale; }

};

class Employee { private: std::string m_strEmployer; double m_dWage; public: Employee(std::string strEmployer, double dWage) : m_strEmployer(strEmployer), m_dWage(dWage) { } std::string GetEmployer() { return m_strEmployer; } double GetWage() { return m_dWage; } }; // Teacher publicly inherits Person and Employee class Teacher: public Person, public Employee { private: int m_nTeachesGrade; public: Teacher(std::string strName, int nAge, bool bIsMale, std::string strEmployer, double dWage, int nTeachesGrade) : Person(strName, nAge, bIsMale), Employee(strEmployer, dWage), m_nTeachesGrade(nTeachesGrade) { } };

Set 2. Q 2. Discuss the types of Inheritance with suitable example for each.
Ans:

Moumita Mondal. MCA-2nd sem

11 MC0066 OOPS USING C++


Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class.

Types of Inheritance: There are five different inheritances supported in C++: (1) Simple / Single (2) Multilevel (3) Hierarchical (4) Multiple (5) Hybrid

1) PROGRAM: PAYROLL SYSTEM USING SINGLE INHERITANCE: #include<iostream.h> #include<conio.h> class emp { public: int eno; char name[20],des[20]; void get() { cout<<"Enter the employee number:"; cin>>eno; cout<<"Enter the employee name:"; cin>>name; cout<<"Enter the designation:"; cin>>des;

Moumita Mondal. MCA-2nd sem

12 MC0066 OOPS USING C++


} }; class salary:public emp { float bp,hra,da,pf,np; public: void get1() { cout<<"Enter the basic pay:"; cin>>bp; cout<<"Enter the Humen Resource Allowance:"; cin>>hra; cout<<"Enter the Dearness Allowance :"; cin>>da; cout<<"Enter the Profitablity Fund:"; cin>>pf; } void calculate() { np=bp+hra+da-pf; } void display() { cout<<eno<<"\t"<<name<<"\t"<<des<<"\t"<<bp<<"\t"<<hra<<"\t"<<da<<"\t" <<pf<<"\t"<<np<<"\n"; } }; void main() { int i,n; char ch; salary s[10]; clrscr(); cout<<"Enter the number of employee:"; cin>>n; for(i=0;i<n;i++) { s[i].get(); s[i].get1(); s[i].calculate(); } cout<<"\ne_no \t e_name\t des \t bp \t hra \t da \t pf \t np \n"; for(i=0;i<n;i++) { s[i].display(); } getch(); } Output: Enter the Number of employee:1

Moumita Mondal. MCA-2nd sem

13 MC0066 OOPS USING C++


Enter Enter Enter Enter Enter Enter Enter the the the the the the the employee No: 150 employee Name: ram designation: Manager basic pay: 5000 HR allowance: 1000 Dearness allowance: 500 profitability Fund: 300

E.No E.name des BP HRA DA PF NP 150 ram Manager 5000 1000 500 300 6200 2) Example of Multilevel Inheritance:
#include< iostream.h> #include< conio.h> class student // Base Class { protected: int rollno; char *name; public: void getdata(int b,char *n) { rollno = b; name = n; } void putdata(void) { cout< < " The Name Of Student \t: "< < name< < endl; cout< < " The Roll No. Is \t: "< < rollno< < endl; } }; class test:public student // Derieved Class 1 { protected: float m1,m2; public: void gettest(float b,float c) { m1 = b; m2 = c; } void puttest(void) { cout< < " Marks In CP Is \t: "< < m1< < endl; cout< < " Marks In Drawing Is \t: "< < m2< < endl; } }; class result:public test // Derieved Class 2 { protected: float total; public: void displayresult(void)

Moumita Mondal. MCA-2nd sem

14 MC0066 OOPS USING C++


{ total = m1 + m2; putdata(); puttest(); cout< < " Total Of The Two \t: "< < total< < endl; } }; void main() { clrscr(); int x; float y,z; char n[20]; cout< < "Enter Your Name:"; cin>>n; cout< < "Enter The Roll Number:"; cin>>x; result r1; r1.getdata(x,n); cout< < "ENTER COMPUTER PROGRAMMING MARKS:"; cin>>y; cout< < "ENTER DRAWING MARKS:"; cin>>z; r1.gettest(y,z); cout< < endl< < endl< < "************ RESULT **************"< < endl; r1.displayresult(); cout< < "**********************************"< < endl; getch(); } /************ OUTPUT ************ Enter Your Name:Lionel Enter The Roll Number:44 ENTER COMPUTER PROGRAMMING MARKS:95 ENTER DRAWING MARKS:90 ************ RESULT ************** The Name Of Student : Lionel The Roll No. Is : 44 Marks In CP Is : 95 Marks In Drawing Is : 90 Total Of The Two : 185 **********************************

3) Example of Hierarchical Inheritance: #include <iostream.h> class Side { protected: int l; public: void set_values (int x) { l=x;} };

Moumita Mondal. MCA-2nd sem

15 MC0066 OOPS USING C++


class Square: public Side { public: int sq() { return (l *l); } }; class Cube:public Side { public: int cub() { return (l *l*l); } }; int main () { Square s; s.set_values (10); cout << "The square value is::" << s.sq() << endl; Cube c; c.set_values (20); cout << "The cube value is::" << c.cub() << endl; return 0; } Result: The square value is:: 100 The cube value is::8000

#include <string> class Person { private: std::string m_strName; int m_nAge; bool m_bIsMale;

4) Example of multiple Inheritance:

public: Person(std::string strName, int nAge, bool bIsMale) : m_strName(strName), m_nAge(nAge), m_bIsMale(bIsMale) { } std::string GetName() { return m_strName; } int GetAge() { return m_nAge; } bool IsMale() { return m_bIsMale; } }; class Employee { private: std::string m_strEmployer;

Moumita Mondal. MCA-2nd sem

16 MC0066 OOPS USING C++


double m_dWage; public: Employee(std::string strEmployer, double dWage) : m_strEmployer(strEmployer), m_dWage(dWage) { } std::string GetEmployer() { return m_strEmployer; } double GetWage() { return m_dWage; } }; // Teacher publicly inherits Person and Employee class Teacher: public Person, public Employee { private: int m_nTeachesGrade; public: Teacher(std::string strName, int nAge, bool bIsMale, std::string strEmployer, double dWage, int nTeachesGrade) : Person(strName, nAge, bIsMale), Employee(strEmployer, dWage), m_nTeachesGrade(nTeachesGrade) { } }; 5) Example of Hybrid Inheritance: #include <iostream.h> class mm { protected: int rollno; public: void get_num(int a) { rollno = a; } void put_num() { cout << "Roll Number Is:"<< rollno << "\n"; } }; class marks : public mm { protected: int sub1; int sub2; public: void get_marks(int x,int y) { sub1 = x; sub2 = y;

Moumita Mondal. MCA-2nd sem

17 MC0066 OOPS USING C++


} void put_marks(void) { cout << "Subject 1:" << sub1 << "\n"; cout << "Subject 2:" << sub2 << "\n"; } }; class extra { protected: float e; public: void get_extra(float s) {e=s;} void put_extra(void) { cout << "Extra Score::" << e << "\n";} }; class res : public marks, public extra{ protected: float tot; public: void disp(void) { tot = sub1+sub2+e; put_num(); put_marks(); put_extra(); cout << "Total:"<< tot; } }; int main() { res std1; std1.get_num(10); std1.get_marks(10,20); std1.get_extra(33.12); std1.disp(); return 0; } Result: Roll Number Is: 10 Subject 1: 10 Subject 2: 20 Extra score:33.12 Total: 63.12

Moumita Mondal. MCA-2nd sem

18 MC0066 OOPS USING C++

.. Set 2. Q 3. Write a c++ program to implements the relational operator overloading for the distance class.
Ans: The following program implements the program for < relational operator overloading for the distance class. # include<iostream.h> class distance { private: int feet, inches; public: distance() {feet=0; inches=0;} distance(int f) {feet=f; inches=0;} distance(int f, int i) {feet=f;inches=i;} void display(); void getdata(); int operator < (distance d1) { if (feet<d1.feet) return 1; else if (feet==d1.feet) && (inches<d1.inches) return 1; else return 0; } }; void distance :: display() {cout<<feet <<" "<<inches<<endl;} void distance :: getdata() { cout<<Enter distance in feet and inches; cin>>feet >>inches;} void main() { distance d1,d2; d1.getdata(); d2.getdata(); if (d1<d2) cout<<d1.display() << is smaller; else cout<<d2.display()<< is smaller; } In the above program the d1 object invokes the operator < and d2 is passed as an argument. The return value is either 0 or 1 which indicates false or true respectively. Certain compilers support boolean datatype which can be alternatively used instead of integer. The above program also implements display and getdata member functions differently. The member functions are declared inside the class but are defined outside the class. But to specify that the member function belongs to the distance class, the class name is included along with the function name separated by the scope resolution operator (::). ..

Moumita Mondal. MCA-2nd sem

19 MC0066 OOPS USING C++

Set 2. Q 4. Write the advantages of using exception handling with its basic models.
Ans: Advantage 1: Separating Error-Handling Code from "Regular" Code Exceptions provide the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. For example, consider the pseudocode method here that reads an entire file into memory. readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } At first glance, this function seems simple enough, but it ignores all the following potential errors. 1. What happens if the file can't be opened? 2. What happens if the length of the file can't be determined? 3. What happens if enough memory can't be allocated? 4. What happens if the read fails? 5. What happens if the file can't be closed? To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. Here is an example of what the function might look like. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; }

Moumita Mondal. MCA-2nd sem

20 MC0066 OOPS USING C++


} else { errorCode = -5; } return errorCode; } There's so much error detection, reporting, and returning here that the original seven lines of code are lost in the clutter. Worse yet, the logical flow of the code has also been lost, thus making it difficult to tell whether the code is doing the right thing: Is the file really being closed if the function fails to allocate enough memory? It's even more difficult to ensure that the code continues to do the right thing when you modify the method three months after writing it. Many programmers solve this problem by simply ignoring it errors are reported when their programs crash. Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere. If the readFile function used exceptions instead of traditional error-management techniques, it would look more like the following. readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively. Advantage 2: Propagating Errors Up the Call Stack A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2, which calls method3, which finally calls readFile. method1 { call method2; } method2 { call method3; } method3 { call readFile; } Suppose also that method1 is the only method interested in the errors that might occur within readFile. Traditional error-notification techniques force method2 and method3 to propagate the error codes returned

Moumita Mondal. MCA-2nd sem

21 MC0066 OOPS USING C++


by readFile up the call stack until the error codes finally reach method1the only method that is interested in them. method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } Recall that the Java runtime environment searches backward through the call stack to find any methods that are interested in handling a particular exception. A method can duck any exceptions thrown within it, thereby allowing a method farther up the call stack to catch it. Hence, only the methods that care about errors have to worry about detecting errors. method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } However, as the pseudocode shows, ducking an exception requires some effort on the part of the middleman methods. Any checked exceptions that can be thrown within a method must be specified in its throws clause. Advantage 3: Grouping and Differentiating Error Types Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy. An example of a group of related exception classes in the Java platform are those defined in java.io IOException and its descendants. IOException is the most general

Moumita Mondal. MCA-2nd sem

22 MC0066 OOPS USING C++


and represents any type of error that can occur when performing I/O. Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk. A method can write specific handlers that can handle a very specific exception. The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception. catch (FileNotFoundException e) { ... } A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument. catch (IOException e) { ... } This handler will be able to catch all I/O exceptions, including FileNotFoundException, EOFException, and so on. You can find details about what occurred by querying the argument passed to the exception handler. For example, use the following to print the stack trace. catch (IOException e) { e.printStackTrace(); //Output goes to System.err. e.printStackTrace(System.out); //Send trace to stdout. } You could even set up an exception handler that handles any Exception with the handler here. catch (Exception e) { //A (too) general exception handler ... } The Exception class is close to the top of the Throwable class hierarchy. Therefore, this handler will catch many other exceptions in addition to those that the handler is intended to catch. You may want to handle exceptions this way if all you want your program to do, for example, is print out an error message for the user and then exit. In most situations, however, you want exception handlers to be as specific as possible. The reason is that the first thing a handler must do is determine what type of exception occurred before it can decide on the best recovery strategy. In effect, by not catching specific errors, the handler must accommodate any possibility. Exception handlers that are too general can make code more errorprone by catching and handling exceptions that weren't anticipated by the programmer and for which the handler was not intended. As noted, you can create groups of exceptions and handle exceptions in a general fashion, or you can use the specific exception type to differentiate exceptions and handle exceptions in an exact fashion.

. Set 2. Q 5. Discuss the various STL components in brief.


Ans: Containers : STL provides a number of container types, representing objects that contain other objects. The STL contains sequence containers and associative containers. The standard sequence containers

Moumita Mondal. MCA-2nd sem

23 MC0066 OOPS USING C++


include vector, deque and list. sequence containers in, as their name suggests, store data in linear sequence The standard associative containers are set, multiset, map and multimap. Associative containers are a generalization of sequences. Sequences are indexed by integers; associative containers can be indexed by any type. Other types of containers are bitset (stores series of bits similar to a fixed-sized vector of bools, also optimizes for space), and valarray (another C-like array like vector, but is designed for high speed numerics at the expense of some programming ease and general purpose use. It has many features that make it ideally suited for use with vector processors in traditional vector supercomputers and SIMD units in consumer-level scalar processors, and also ease vector mathematics programming even in scalar computers). Iterators : Iterators are like location specifiers for containers or streams of data, in the same way that an int* can be used as a location specifier for an array of integers, or an ifstream can be used as a location specifier for a file. The STL implements five different types of iterators. These are input iterators (which can only be used to read a sequence of values), output iterators (which can only be used to write a sequence of values), forward iterators (which can be read, written to, and move forward), bidirectional iterators (which are like forward iterators but can also move backwards) and random access iterators (which can move freely any number of steps in one operation). It is possible to have bidirectional iterators act like random access iterators, as moving forward ten steps could be done by simply moving forward a step at a time a total of ten times. However, having distinct random access iterators offers efficiency advantages. For example, a vector would have a random access iterator, but a list only a bidirectional iterator. Iterators are the major features which allow the generality of the STL. For example, an algorithm to reverse a sequence can be implemented using bidirectional iterators, and then the same implementation can be used on lists, vectors and deques. User-created containers only have to provide an iterator which implements one of the 5 standard iterator interfaces, and all the algorithms provided in the STL can be used on the container. This generality also comes at a price at times. For example, performing a search on an associative container such as a map or set can be much slower using iterators than by calling member functions offered by the container itself. This is because an associative container's methods can take advantage of knowledge of the internal structure, which is opaque to algorithms using iterators. Algorithms : The STL algorithms are template C++ functions to perform operations on containers. In order to be able to work with many different types of containers, the algorithms do not take containers as arguments. Instead, they take iterators that specify part or all of a container. In this way the algorithms can be used to work on entities that are not containers; for example, the function copy can be used to copy data from standard input into a vector. A large number of algorithms to perform operations such as searching and sorting are provided in the STL; each implemented to require a certain level of iterator (and therefore will work on any container which provides an interface by iterators). The algorithms include sorting operations (sort, merge, min, max, etc.), searching operations (find, count, equal, etc.), mutating operations (transform, replace, fill, rotate, shuffle), and generalized numeric operations (accumulate, adjacent difference, etc.). Functors : The STL includes classes that overload the function operator (operator()). Classes that do this are called functors or function objects. They are useful for keeping and retrieving state information in functions passed into other functions. Regular function pointers can also be used as functors. Function objects are STL's way of representing "executable data". For example, one of the STL algorithms is for_each. This applies a function to each object in a container. You need to be able to specify what to do to each object in the container. ..

Moumita Mondal. MCA-2nd sem

24 MC0066 OOPS USING C++


Set 2. Q 6. Describe the time overhead of operations on sequence containers.
Ans: There are three types of sequence containers in the STL. These, as their name suggests, store data in linear sequence. They are the vector, deque and list:

list<Type> To choose a container, decide what sort of operations you will most frequently perform on your data, then use the following table to help you. Operation Access 1st 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

vector<Type> deque<Type>

Time overhead of operation on secuence containers Each container has attributes suited to particular applications. The subsections and code samples below should further clarify when and how to use each type of sequence container. Vector #include <vector> The vector class is similar to an array, and allows array-type syntax, e.g. my_vector[2] . A vector is able to access elements at any position (referred to as "random" access in the preceding table) with a constant time overhead, O(1). Insertion or deletion at the end of a vector is "cheap". As with the string, no bounds checking is performed when you use operator []. Insertions and deletions anywhere other than at the end of the vector incur overhead O(N), N being the number of elements in the vector, because all the following entries have to be shuffled along to make room for the new entries, the storage being contiguous. Memory overhead of a vector is very low and comparable to a normal array. Deque #include <deque> The double-ended queue, deque (pronounced "deck") has similar properties to a vector, but as the name suggests you can efficiently insert or delete elements at either end. A deque, like a vector, is not very good at inserting or deleting elements at random positions, but it does allow random access to elements using the arraylike[] syntax, though not as efficiently as a vector or array. Like the vector an erase() or insert() in the middle can invalidate all existing iterators. List #include <list>

Moumita Mondal. MCA-2nd sem

25 MC0066 OOPS USING C++

Lists don't provide [] random access like an array or vector, but are suited to applications where you want to add or remove elements to or from the middle. They are implemented as double linked list structures in order to support bidirectional iterators, and are the most memory-hungry standard container, vector being the least so. In compensation, lists allow low-cost growth at either end or in the middle. ..

Set 2. Q 7. Discuss how object diagrams are different from class diagram.
Ans: Object Diagram: Object diagrams are derived from class diagrams so object diagrams are dependent upon class diagrams. Object diagrams represent an instance of a class diagram. The basic concepts are similar for class diagrams and object diagrams. Object diagrams also represent the static view of a system but this static view is a snapshot of the system at a particular moment. Object diagrams are used to render a set of objects and their relationships as an instance. Purpose: The purpose of a diagram should be understood clearly to implement it practically. The purposes of object diagrams are similar to class diagrams. The difference is that a class diagram represents an abstract model consisting of classes and their relationships. But an object diagram represents an instance at a particular moment which is concrete in nature. It means the object diagram is more close to the actual system behaviour. The purpose is to capture the static view of a system at a particular moment. So the purpose of the object diagram can be summarized as: Forward and reverse engineering. Object relationships of a system Static view of an interaction. Understand object behaviour and their relationship from practical perspective

Class Diagram:
The class diagram is a static diagram. It represents the static view of an application. Class diagram is not only used for visualizing, describing and documenting different aspects of a system but also for constructing executable code of the software application. The class diagram describes the attributes and operations of a class and also the constraints imposed on the system. The class diagrams are widely used in the modelling of object oriented systems because they are the only UML diagrams which can be mapped directly with object oriented languages. The class diagram shows a collection of classes, interfaces, associations, collaborations and constraints. It is also known as a structural diagram.

Moumita Mondal. MCA-2nd sem

26 MC0066 OOPS USING C++


Purpose: The purpose of the class diagram is to model the static view of an application. The class diagrams are the only diagrams which can be directly mapped with object oriented languages and thus widely used at the time of construction. The UML diagrams like activity diagram, sequence diagram can only give the sequence flow of the application but class diagram is a bit different. So it is the most popular UML diagram in the coder community. So the purpose of the class diagram can be summarized as: Analysis and design of the static view of an application. Describe responsibilities of a system. Base for component and deployment diagrams. Forward and reverse engineering.

..

Moumita Mondal. MCA-2nd sem

Das könnte Ihnen auch gefallen