S.E Computer (First Semester) Examination 2016 OBJECT ORIENTED PROGRAMMING (2015 Pattern) Nov / Dec 2016 Time : 2 Hours Maximum Marks : 50

Q.1 a) Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) 4M Procedure Oriented Programming Object Oriented Programming

In POP, program is divided into small In OOP, program is divided into parts Divided Into parts called functions. called objects. In POP,Importance is not given to data In OOP, Importance is given to the data Importance but to functions as well as sequence of rather than procedures or functions actions to be done. because it works as a real world. Approach POP follows Top Down approach. OOP follows Bottom Up approach. Access OOP has access specifiers named POP does not have any access specifier. Specifiers Public, Private, Protected, etc. In OOP, objects can move and In POP, Data can move freely from Data Moving communicate with each other through function to function in the system. member functions. To add new data and function in POP is OOP provides an easy way to add new Expansion not so easy. data and function. In OOP, data can not move easily from In POP, Most function uses Global data function to function,it can be kept public Data Access for sharing that can be accessed freely or private so we can control the access from function to function in the system. of data. POP does not have any proper way for OOP provides Data Hiding so provides Data Hiding hiding data so it is less secure. more security. In OOP, overloading is possible in the Overloading In POP, Overloading is not possible. form of and . Example of POP are : C, VB, Example of OOP are : C++, JAVA, Examples FORTRAN, Pascal. VB.NET, C#.NET.

Q.1 b) What is friend function? 2M Ans. A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend as follows: class Box { double width; public: double length; friend void printWidth( Box box ); void setWidth( double wid ); };

Q.1 c) Define class number which has inline function mult() and cube( ) for calculating the multiplication of two double numbers given and cube of the integer number given? 4M Ans c) #include #include class number { public: inline float mul(double x,double y) { return(x*y); } inline float cube(int x) { return(x*x*x); } }; void main() { number obj; double val1,val2; int val3; clrscr(); cout<<"Enter two double values and one integer value:"; cin>>val1>>val2>>val3; cout<<"\Multiplication value is:"<

Q.1 d) What is use of this pointer? 2M Ans . i. The ‘this’ pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. ii. ‘this’ pointer is a constant pointer that holds the memory address of the current object. Use : 1) When local variable’s name is same as member’s name class Test { private: int x; public: void setX (int x) { // The 'this' pointer is used to retrieve the object's x hidden by the local //variable 'x' this->x = x; } void print() { cout << "x = " << x << endl; } }; 2) To return reference to the calling object Test& Test::func () { // Some processing return *this; }

Or

Q.2 a) Discuss the various ways in which inheritance promotes software reuse, saves time during program development and helps prevent errors. [4] 1) Inheritance allows developers to create subclasses that reuse code declared already in a superclass. 2) Avoiding the duplication of common functionality between several classes by building a class inheritance hierarchy can save developers a considerable amount of time. 3) Similarly, placing common functionality in a single superclass, rather than duplicating the code in multiple unrelated classes, helps prevent the same errors from appearing in multiple source-code files. If errors occur in the common functionality of the superclass, the software developer needs to modify only the superclass’s.

Q.2 b) Define a class string. use overloaded == operator to compare two strings 5M Ans. #include #include #include class string { public: char *s; void getstring(char *str) { strcpy(s,str); }

void operator==(comp); }; void comp::operator==(comp ob) { if(strcmp(s,ob.s)==0) cout<<"\nStrings are Equal"; else cout<<"\nStrings are not Equal"; } void main() { comp ob, ob1; char *string1, *string2; clrscr();

cout<<"Enter First String:"; cin>>string1;

ob.getstring(string1);

cout<<"\nEnter Second String:"; cin>>string2;

ob1.getstring(string2);

//Call Equality Operator ob==ob1; getch(); }

Q.2 c) Explain abstract class with an example 3M Ans. Abstract class in C++ programming is a class that contains at least one pure virtual function. (Pure virtual function in C++ is a virtual functions with no implementation). It may also contain non-virtual functions and member variables. Pure virtual functions in abstract class is implemented by its derived classes.

Main important point of an abstract class is that we cannot create an object of it, but we create a pointer. And, in this pointer, we assign the object of derived classes. /Abstract base class class AbstractBase { public: virtual void Display() = 0; //Pure Virtual Function declaration };

//Derived class that will inherit the abstract base class // and implement pure virtual function. class Derived:public AbstractBase { public: void Display() { cout << "pure virtual function implementation"; } };

//------TEST-Abstract Class ------

int main() {

AbstractBase *basePointer = new Derived(); basePointer->Display();

// OR AbstractBase * bPtr; Derived dObj; bPtr = &dObj; bPtr->Display();

//Abstract base class object can't be created. //AbstractBase obj; // Compiler will flash an error.

}

Q.3 a) How smart pointers avoid the problem of memory leak? 4M Ans. 1. Smart pointers are an improved, more reliable way to manage resources such as dynamically allocated memory and file handles. 2. A smart pointer is a "wrapper" that contains a pointer within it but also performs other special actions. This data type causes an internal reference count to be kept for the associated memory object. The count is equal to the total number of pointers that refer to the object. When the count reaches zero, the object is destroyed, and the memory is released. For Eg.

#include using namespace std; class SmartPtr { int *ptr; // Actual pointer public: // Constructor explicit SmartPtr(int *p = NULL) { ptr = p; }

// Destructor ~SmartPtr() { delete(ptr); } // Overloading dereferencing operator int &operator *() { return *ptr; } int *operator ->() //Overloading Access operator { return ptr; } }; int main() { SmartPtr ptr(new int()); *ptr = 20; cout << *ptr;

// We don't need to call delete ptr: when the object // ptr goes out of scope, destructor for it is automatically // called and destructor does delete ptr.

return 0; }

Q.3 b) Differentiate compile time and run-time polymorphism ? 4M Ans. Compile time Polymorphism Run time Polymorphism In Compile time Polymorphism, call is In Run time Polymorphism, call is not resolved by the compiler. resolved by the compiler. It is also known as Static binding, Early It is also known as Dynamic binding, Late binding and overloading as well. binding and overriding as well. Overloading is compile time polymorphism Overriding is run time polymorphism where more than one methods share the having same method with same parameters same name with different parameters or or signature, but associated in a class & its signature and different return type. subclass. It is achieved by function overloading and It is achieved by virtual functions and operator overloading. pointers. It provides slow execution as compare to It provides fast execution because known early binding because it is known at early at compile time. runtime. Compile time polymorphism is less flexible Run time polymorphism is more flexible as as all things execute at compile time. all things execute at run time.

Q.3 c) Explain virtual base class and virtual function with example. 4M Ans Virtual Base Class  An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class.  C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class.  When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base class’ name with the word virtual.  Consider the following example : class A { public: int i; };

class B : virtual public A { public: int j; };

class C: virtual public A { public: int k; };

class D: public B, public C { public: int sum; };

int main() { D ob; ob.i = 10; //unambiguous since only one copy of i is inherited. ob.j = 20; ob.k = 30; ob.sum = ob.i + ob.j + ob.k; cout << “Value of i is : ”<< ob.i<<”\n”; cout << “Value of j is : ”<< ob.j<<”\n”; cout << “Value of k is :”<< ob.k<<”\n”; cout << “Sum is : ”<< ob.sum <<”\n”;

return 0; }

Virtual Functions :  A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the function’s declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs.  Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked.  But if we want to invoke derived class function using base class pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support runtime polymorphism.  Consider the following program code : Class A { int a; public: A() { a = 1; } virtual void show() { cout <

Class B: public A { int b; public: B() { b = 2; } virtual void show() { cout <

Or Q.4 a) Why we need templates in C++ ? 2M Ans. Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

Q.4 b) Explain exception handling mechanism in C++ Write a program in C++ to handle “divide by zero” exception ? 6M Ans. An exception is a problem that arises during the execution of a program. A C++ exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C++ exception handling is built upon three keywords: try, catch, and throw.  throw: A program throws an exception when a problem shows up. This is done using a throw keyword.  catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.  try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try { // protected code }catch( ExceptionName e1 ) { // catch block }catch( ExceptionName e2 ) { // catch block }catch( ExceptionName eN ) { // catch block }

Multiple catch statements can be used to catch different type of exceptions in case the try block raises more than one exception in different situations.

Program : void main() { int no1, no2; try { cout << “Enter two nos:”; cin >> no1 >> no2; if (no2 == 0) throw “Divide by zero”; else throw no1/no2; } catch (char *s) { cout << s; } catch (int ans) { cout << ans; } } - We know that divide by zero is an exception. If user enters second no as zero, the program throws an exception, which is caught and an error message is printed else the answer is printed.

Q.4 c) Explain class template and function template with an example? 4M Ans 1. Templates are the foundation of , which involves writing code in a way that is independent of any particular type. 2. A template is a blueprint or formula for creating a generic class or a function. unction Template

The general form of a template function definition is shown here: template ret-type func-name(parameter list) { // body of function }

Here, type is a placeholder name for a data type used by the function. This name can be used within the function definition.

The following is the example of a function template that returns the maximum of two values:

#include #include using namespace std; template inline T const& Max (T const& a, T const& b) { return a < b ? b:a; } int main () {

int i = 39; int j = 20; cout << "Max(i, j): " << Max(i, j) << endl;

double f1 = 13.5; double f2 = 20.7; cout << "Max(f1, f2): " << Max(f1, f2) << endl;

string s1 = "Hello"; string s2 = "World"; cout << "Max(s1, s2): " << Max(s1, s2) << endl;

return 0; }

If we compile and run above code, this would produce the following result:

Max(i, j): 39 Max(f1, f2): 20.7 Max(s1, s2): World

Class Template

Just as we can define function templates, we can also define class templates. The general form of a generic class declaration is shown here: template class class-name { . . . }

Here, type is the placeholder type name, which will be specified when a class is instantiated. You can define more than one generic data type by using a comma-separated list.

Following is the example to define class Stack<> and implement generic methods to push and pop the elements from the stack:

#include #include #include #include #include using namespace std; template class Stack { private: vector elems; // elements

public: void push(T const&); // push element void pop(); // pop element T top() const; // return top element bool empty() const{ // return true if empty. return elems.empty(); } }; template void Stack::push (T const& elem) { // append copy of passed element elems.push_back(elem); } template void Stack::pop () { if (elems.empty()) { throw out_of_range("Stack<>::pop(): empty stack"); }

// remove last element elems.pop_back(); } template T Stack::top () const { if (elems.empty()) { throw out_of_range("Stack<>::top(): empty stack"); }

// return copy of last element return elems.back(); } int main() { try { Stack intStack; // stack of ints Stack stringStack; // stack of strings

// manipulate int stack intStack.push(7); cout << intStack.top() <

// manipulate string stack stringStack.push("hello"); cout << stringStack.top() << std::endl; stringStack.pop(); stringStack.pop(); }catch (exception const& ex) { cerr << "Exception: " << ex.what() <

If we compile and run above code, this would produce the following result:

7 hello Exception: Stack<>::pop(): empty stack

Q.5 a) What is a stream? Explain types of streams available in C++ 6M Ans  A 'stream' is internally nothing but a series of characters. The characters may be either normal characters (char) or wide characters (wchar_t).  Streams provide you with a universal character-based to any type of storage medium (for example, a file), without requiring you to know the details of how to write to the storage medium.

Types of Streams in C++ : 1. Input Stream  An input stream is a sequence of characters coming from an input source.  When a program needs input, it extracts characters from an input stream.

2. Output Stream  An output stream is a sequence of characters heading for an output sink.  When a program wants to perform output, it inserts characters into an output stream.

Stream Description

cin Standard input stream

cout Standard output stream

cerr Standard error stream

clog Buffered version of cerr

Output Streams

Output streams are instances of the class ostream, which is defined in . Eg. cout.put('b'); cout << 42;

Output File Streams

Writing to a file is easy. Simply declare an instance of the ofstream class. Eg. ofstream fs("data"); fs << "Here are some odd numbers:\n";

Input Streams

Input streams are instances of the istream class. Eg. char c = cin.get(); cin >> x;

Input File Streams

We can construct an input file stream from a file name: Eg. ifstream ifs("data.txt"); double avg(const string& source) { double num, total = 0; int count = 0; ifstream ifs(“data.txt”); // won't work with C++ strings! if (!ifs) error("can't open file"); while (ifs >> num) { total += num; count++; } return total/count; }

Q.5 b) Write a program using open() , eof() and getline( ) member functions to open and read a file content line by line. [7] Ans. // using open(), eof() and getline() member functions

#include #include using namespace std; void main(void) { char filename[70]; ifstream inputfile; char FirstLine[70]; char SecondLine[70]; char ThirdLine[70];

// prompt user for file name to be opened cout<<"Enter the filename to be opened: ";

// read and store the file name cin>>filename;

// test open file for reading inputfile.open(filename);

// if not the end of file if(!inputfile.eof()) { cout<<"\nThe first line of text is: \n"; inputfile.getline(FirstLine, 70); cout<

Output example:

Enter the filename to be opened: C:\readfile.txt The first line of text is: This is readfile.txt file content. Just sample text, opening The second line of text is: for reading by using getline() member function. The third line of text is: There are four lines of text to be read from. Press any key to continue . . . Or Q.6 a) Write a program that returns the size in bytes of a program entered on the command line : 7M $filesize program.txt. Ans. #include #include using namespace std; int main ( int argc, char** argv ) { long begin,end; if( argc < 2 ) { cout << "No file was passed. Usage: filesize program.txt"; return 1; }

ifstream myfile ( argv[1] ); begin = myfile.tellg(); myfile.seekg (0, ios::end); end = myfile.tellg(); myfile.close(); cout << "size is: " << (end-begin) << " bytes.\n"; return 0; }

Q.6 a) What are cin and cout? Explain iostream ? [6] Ans 1. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc, this is called output operation.

The standard output stream (cout)

1. The predefined object cout is an instance of ostream class. 2. The cout object is said to be "connected to" the standard output device, which usually is the display screen. 3. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example.

The standard input stream (cin)

The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example.

#include using namespace std; int main( ) { char name[50];

cout << "Please enter your name: "; cin >> name; cout << "Your name is: " << name << endl;

}

When the above code is compiled and executed, it will prompt you to enter a name. You enter a value and then hit enter to see the result something as follows:

Please enter your name: cplusplus Your name is: cplusplus Iostream 1. to C++ is basically what is to C. 2. iostream - header is used to access the input output built in functions of the language as it is the the “Standard input/output streams library”. 3. Here input-output refers to the fact of taking input command and showing output result in the program. 4. “cin>>” , “cout<<” - these are the member objects of the header. Q.7 a) What is the purpose of the iterator ? Elaborate forward, bi-directional and random – access iterators with suitable examples. [7] Ans 1. The concept of an iterator is fundamental to understanding the C++ Standard Template Library (STL) because iterators provide a means for accessing data stored in container classes such a vector, map, list, etc.

Forward iterators 1. These have all the functionality of input iterators and -if they are not constant iterators- also the functionality of output iterators, 2. They are limited to one direction in which to iterate through a range (forward). 3. All standard containers support at least forward iterator types. 4. Forward iterators allow both reading and writing 5. For example, in the following code instances of the value 7 are replaced with the value 11 in a vector of integers: std::replace(aVec.begin(), aVec.end(), 7, 11);

template void replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) { while (first != last) { if (*first == old_value) *first = new_value; ++first; } }

Bidirectional iterators 1. Bidirectional iterators are like forward iterators but can also be iterated through backwards. 2. A Bidirectional Iterator is an iterator that can be both incremented and decremented. 3. For example, we can use bidirectional iterators in a function that reverses the values of a container, placing the results into a new container:

template OutputIterator reverse_copy(BidirectionalIterator first, BidirectionalIterator last, OutputIterator result) { while (first != last) *result++ = *--last; return result; }

As always, the value initially denoted by the last argument is not considered part of the collection. The reverse_copy() function could be used, for example, to reverse the values of a linked list, and place the result into a vector: std::list aList; .... std::vector aVec (aList.size()); std::reverse_copy(aList.begin(), aList.end(), aVec.begin() );

Random Access Iterators

1. Random-access iterators are iterators that can be used to access elements at an arbitrary offset position relative to the element they point to, offering the same functionality as pointers. 2. It provides both increment and decrement (just like a Bidirectional Iterator) 3. Random Access Iterators provide essentially all of the operations of ordinary C pointer arithmetic. 4. For example, the following algorithm randomly shuffles the elements of a container. This is similar to, although simpler than, the function std::random_shuffle() provided by the C++ Standard Library.

template void mixup(RandomAccessIterator first, RandomAccessIterator last) { while (first < last) { std::iter_swap(first, first + randomInteger(last - first)); ++first; } }

Q.7 b) What is a stack? How is it implemented using STL ? [7] Ans  A stack is an adaptor that provides a restricted subset of Container functionality: it provides insertion, removal, and inspection of the element at the top of the stack.  Stack is a "last in first out" (LIFO) data structure: the element at the top of a stack is the one that was most recently added.  Stack does not allow iteration through its elements.  Stack is a container adaptor, meaning that it is implemented on top of some underlying container type.  By default that underlying type is deque, but a different type may be selected explicitly.

Implementation  To be able to use STL stacks in a file of C++ source code or a header file add o #include at the beginning of the file.  Suppose that T is any type or class - say an int, a float, a struct, or a class, then o stack s; declares a new and empty stack called s.  Given ‘s’ you can: test to see if it is empty: s.empty()  Find how many items are in it: s.size()  Push a t of type T onto the top: s.push(t)  Pop the top off s: s.pop()  Get the top item of s : s.top()  Change the top item: s.top() = expression.

Q.8 a) Elaborate advantages and disadvantages of the following Basic Sequence containers : [6] i) Vector ii) List. Ans Vector : Advantages i. Vectors have low memory usage ii. Vectors allow the user to denote an initial capacity for the container iii. Vectors allow random access : that is, an element of a vector may be referenced in the same manner as elements of arrays iv. inserting and removing elements from the end of the vector is generally fast. Disadvantages i. Erasing elements from a vector or even clearing the vector entirely does not necessarily free any of the memory associated with that element. ii. The reallocation of memory that can be necessary with vectors when new elements are inserted into the list. List Advantages i. Inserting elements into a list is very fast if you already know where you want to insert them ii. Data is stored non-contiguously in memory which allows the list data structure to avoid the reallocation of memory iii. The list data structure allocates and deallocates memory as needed; therefore, it does not allocate memory that it is not currently using

Disadvantages i. Lists only provide access to the start and end of the list -- there is no random access provided ii. With small data types (such as ints) the memory overhead is much more significant than that of a vector

Q.8 b) What is STL? Why should programmer be interested in STL. What is the design philosopy of the STL?What are the major components of STL?[6] Ans The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provides general-purpose templatized classes and functions that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.

Programmers must be interested in STL because a) it is well tested and optimized. b) it is a really big time saver c) STL provides a 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).

Design Philosophy of STL  Generic containers that take the element type as a parameter. - know (almost) nothing about the element type - exception: ordered containers expect elements to have operator< - operations are (mostly) limited to add, remove, and retrieve - define their own iterators

 Useful, efficient, generic algorithms that: - know nothing about the data structures they operate on - know (almost) nothing about the elements in the structures - operate on range of elements accessed via iterators

 STL algorithms are designed so that (almost) any algorithm can be used with any STL container, or any other data structure that supports iterators. − Element type must support copy constructor/assignment. • For ordered containers, the element type must support operator< or you can provide a special functor (function-object) of your own. • The STL assumes value semantics for its contained elements: elements are copied to/from containers more than you might realize. • The container methods and algorithms are highly efficient; it is unlikely that you could do better.

Core of the C++ Standard Template Library are following three well-structured components: Component Description Containers are used to manage collections of objects of a certain Containers kind. There are several different types of containers like deque, list, vector, map etc. Algorithms act on containers. They provide the means by which Algorithms you will perform initialization, sorting, searching, and transforming of the contents of containers. Iterators are used to step through the elements of collections of Iterators objects. These collections may be containers or subsets of containers.