You are on page 1of 19

Name Roll Number Learning Centre Systems

Puneet Marwah : 511222482 : : Advance Learning

Learning Code Centre Course Semester Subject : :

02882, Noida

MCA : 2nd Semester

OOPS using C++ : : : 1 , 2012

Module No. (Set No.) Date of Submission Faculty Signature

June

Directorate of Distance Education Sikkim Manipal University 2nd Floor, Syndicate House Manipal-576104

Spring 2012

Master of Computer Application (MCA) Semester II MC0066 OOPS using C++ - 4 credits
(Book ID: B0681 & B0715) Assignment Set 1 (40 Marks)
Question from Book ID: B0681 Q1 Distinguished between Procedural Language and OOP Language. And explain the key features of OOP. [ 5 Marks ] A1 Procedural approach for programming had several problems as the size of the softwares grew larger and larger. One of the main problems was data being completely forgotten. Data in the program was created by variables and if more than one functions had to access data, global variables were used. The concept of global variables itself is a problem as it may be accidentally modified by an undesired function. This also leads to difficulty in debugging and modifying the program when several functions access a particular data. The object oriented approach overcomes this problem by modelling data and functions together there by allowing only certain functions to access the required data. 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. For example, if the programmer had to define his own version of string and define how this new datatype will be manipulated, it would be difficult. The object oriented programming provides this flexibility through the concept of class. Another limitation of the procedural languages is that the program model is not close to real world objects. For example, if you want to develop a gaming application of car race, what data would you use and what function you would require is difficult questions to answer in a procedural approach. 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. Q2 What is function overloading. Write a C++ program to implement a function overload. [ 5 Marks ] A2 More than one user defined functions can have same name and perform different operations. This is a powerful feature of C++ and is known as Function Overloading. Every overloaded function should however have a different prototype. The following program implements an overloaded function.

printline() //fnoverload.cpp #include <iostream.h> void printline(); void printline(char ch); void printline(char ch, int n)l; void main() { printline(); printline(*); printline(*,20); } void printline(); { for(int i=0;i<25;i++) cout<<-; cout<<endl; } void printline(char ch) { for(int i=0;i<25;i++) cout<<ch; cout<<endl; } void printline(char ch, int n) { for (int i=0;i<n;i++) cout<<ch; cout<<endl; } In the above program, the function printline() has three different prototypes depending on the arguments passed to it. The relevant function is invoked depending on the type and number of arguments passed to it. Q3 Discuss the constructors and destructors with suitable examples. [ 5 Marks ] A3 Constructors are member functions of a class which have same name as the class name. Constructors are called automatically whenever and 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.

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 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. The following program implements the constructor and destructors for a class: //constdest.cpp #include <iostream.h> class sample { private: int data; public: sample(){data=0;cout<<Constructor invoked<<endl;} ~sample(){cout<<Destructor invoked;} void display() { cout<<Data=data<<endl; } }; void main() { sample obj1; obj.display(); } If you run the above program you will get the output as follows: Constructor invoked Data=0 Destructor invoked When object of sample class, obj is created, automatically the constructor is invoked and data is initialized to zero. When the program ends the object is destroyed which invokes the destructor. Q4 What do you mean by operator overloading? Illustrate with suitable example for overloading Unary operators. [ 5 Marks ] A4 Operator overloading is an interesting feature of C++ that allows programmes 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. It helps to use the default operators with the user defined objects for making the code simpler.

There are several problems with operator overloading, which you should be aware of. When using operator overloading, the operator should perform only the most obvious function. Otherwise it will lead to more confusion. If you are overloading + operator for distance class it should add two distance objects, and should not do something else. Operator overloading works similar to any member function of a class. But it is not invoked using dot operator. Just like member function the operator has a return value and takes arguments. It is invoked by the operand which uses it. In case of overloading of unary operations, the calling operand can be either left or right of the operator like in case of increment and decrement operators. Let us overload the increment operator for a class: //unary.cpp #include <iostream.h> class counter { unsigned int count; public: counter() { count=0; } int getcount() { return count; } void operator ++() { count++; } }; void main() { counter c1; c1++; ++c1; cout<<c1.getcount(); } In the above example, the operator ++ is defined to return void and take no arguments. All unary operators do not take no arguments as it operates on only one operand and that operand itself invokes the operator. Therefore the operand is send by default.

Question from Book ID: B0715 Q5 Write C++ program which demonstrate the difference between static and dynamic binding. [ 5 Marks ] A5 In the most general terms, static binding means that references are resolved at compile time. Animal a = new Animal(); a.Roar(); // The compiler can resolve this method call statically. Dynamic binding means that references are resolved at run time. public void MakeSomeNoise(object a) { // Things happen... ((Animal) a).Roar(); // You won't know if this works until runtime! } In static binding, at compile time itself method definition is bound to the method call but in dynamic binding at run time the binding happens. i.e., at run time based on the actual object the method definition is bound to the method call. In C++, class Base { void Foo() { // some code } } class Derived:Base // Derived is a class deriving from Base class { void Foo() { // some code } void main() { Base b; Derived d; b.Foo(); // static binding, and calls Base.Foo() d.Foo(); // static binding, and calls Derived.Foo() Base *pb; pb=new Base(); pb.Foo(); // static binding, and calls Base.Foo() because the pointer is of type Base pb=new Derived();

pb.Foo(); // static binding , and calls Derived.Foo() because the pointer is of type Base } } But if the Foo() function in Base class is virtual, then Base *pb=new Derived(); pb->Foo(); //Dynamic binding, and calls Derived.Foo() Q6 Difference between a static member function and non-static member functions with appropriate example. [ 5 Marks ] A6 A non-static member function is invoked on objects of the class it belongs to. It has implicitly access to the this pointer representing the current object. Through this pointer, it may access other members easily and with full access privileges (i.e. access private members). A non-member function has no implicit this. In the sample below, bar is a member function while freebar is not. Both do more or less the same, but note how bar gets an implicit object pointer via this (also only bar has privileged access to foo's members, freebar only has access to public members). class foo { public: void bar() { this->x = 0; // equivalent to x = 0; } int x; }; void freebar(foo* thefoo) { thefoo->x = 1; } // ... foo f; f.bar(); // f.x is now 0 freebar(&f); // f.x is now 1 Semantically a member function is more than just a function with an implicit this parameter. It is meant to define the behaviour of an object (i.e. a car object would have drive(), stop() as member functions). Note that there are also static member functions which have full privileges but

don't get an implicit this nor are they invoked through an instance of the class (but rather through the full name of the class). Q7 Write C++ program to demonstrate the complete implementation of class template stack. [ 5 Marks ] A7 A class template definition looks like a regular class definition, except it is prefixed by the keyword template. For example, here is the definition of a class template for a Stack. template <class T> class Stack { public: Stack(int = 10); ~Stack(){delete[] stackPrt;} int push(const T&); int pop(T&); int isEmpy() const{return top == -1;} int isFull() const{return top == size 1;} private: int size; // number of elements on Stack. int top; T* stackPtr; }; Q8 What is template specialization? Describe a scenario in which template class partial specialization is considered appropriate. [5 Marks ] A8 In some cases it is possible to override the template-generated code by providing special definitions for specific types. This is called template specialization. The following example defines a template class specialization for template class stream. Template Class Partial 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.

Name Roll Number Learning Centre Systems

Puneet Marwah : 511222482 : : Advance Learning

Learning Code Centre Course Semester Subject : :

02882, Noida

MCA : 2nd Semester

OOPS using C++ : : : 2 , 2012

Module No. (Set No.) Date of Submission Faculty Signature

June

Directorate of Distance Education Sikkim Manipal University 2nd Floor, Syndicate House Manipal-576104

Spring 2012

Master of Computer Application (MCA) Semester II MC0066 OOPS using C++ - 4 credits
(Book ID: B0681 & B0715) Assignment Set 2 (40 Marks)
Question from Book ID: B0681 Q1 Write advantage of multiple inheritances. And write a C++ program to implement the multiple inheritances. [ 10 Marks ] A1 Inheritance is a very powerful feature of object oriented programming. It allows reuse of code without modifying the original code. 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. Inheritance feature has enabled to distribute class libraries which allows the programmer to use the standard code developed by some another company. Inheritance is the process of creating new classes known as derived classes from the existing or base class. The features of the base class are said to be inherited by the derived class. The child class has all the functionality of the parent class and has additional functionalities of its own. The following program, implements the inheritance. The class manager is inherited from the class employee. //inheritance.cpp #include <iostream.h> #include <string.h> #include <conio.h> class employee { protected: int empno; char ename[25]; public: employee() { empno=0; strcpy(ename,); } void display() { cout<<Emp Code:<<empno; cout<<Name:<<ename;

} }; class manager: public employee { protected: float basic; float hra; public: manager():employee() { basic=0.0; hra=0.0; } manager(int n, char ch[25], float i, float j): employee(n,ch) { basic = i; hra = j; } void display() { employee::display(); cout<<Basic<<basic<<endl; cout<<HRA<<hra<<endl; } }; void main() { clrscr(); employee e1(106,amit); manager m1(205,pawan,40000.00,5000.00); e1.display(); m1.display(); getch(); } Q2 Discuss the types of Inheritance with suitable example for each. [ 5 Marks ] A2 Types of Inheritance:-

Single inheritance with one base and derived class. We can have several classes derived from a single base class like shown below.
Shape

Circle

Rectangle

Triangle

This figure shows hierarchical inheritance example. Inheritance can also be multilevel inheritance where another class is derived from the derived class. In such case the grand child class inherits all the properties of child and parent classes.

Shape

Rectangle

Rounded Rectangle

This figure shows Multilevel Inheritance. The derived class can also have multiple parents which is known as multiple inheritance. Here the child or derived class has two or more parent classes. The child class inherits all the properties of all its parents.
Student Employee

Manager

This figure shows multiple inheritance. This is useful in instances when you want to create an employee whose educational qualifications need not be stored such as worker.

Q3 Write a C++ program to implements the relational operator overloading for the distance class. [ 5 Marks ] A3 There are various relational operators supported by C++ language like (<, >, <=, >=, ==, etc.) which can be used to compare C++ built-in data types. You can overload any of these operators, which can be used to compare the objects of a class. Following example explain how a < operator can be overloaded and similar way you can overload other relational operators: #include <iostream> using namespace std; class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance(){ feet = 0; inches = 0; } Distance(int f, int i){ feet = f; inches = i; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } // overloaded < operator bool operator <(const Distance& d) { if(feet < d.feet)

{ return true; } if(feet == d.feet && inches < d.inches) { return true; } return false; } }; int main() { Distance D1(11, 10), D2(5, 11); if( D1 < D2 ) { cout << "D1 is less than D2 " << endl; } else { cout << "D2 is less than D1 " << endl; } return 0; } When the above code is compiled and executed, it produces following result: D2 is less than D1 Question from Book ID: B0715 Q4 Write the advantages of using exception handling with its basic models. [ 5 Marks ] A4 Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers. To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored. An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block:

// exceptions #include <iostream> using namespace std; int main () { try { throw 20; } catch (int e) { cout << "An exception occurred. Exception Nr. " << e << endl; } return 0; } Output: An exception occurred. Exception Nr. 20 The code under exception handling is enclosed in a try block. In this example this code simply throws an exception: throw 20; A throw expression accepts one parameter (in this case the integer value 20), which is passed as an argument to the exception handler. The exception handler is declared with the catch keyword. As you can see, it follows immediately the closing brace of the try block. The catch format is similar to a regular function that always has at least one parameter. The type of this parameter is very important, since the type of the argument passed by the throw expression is checked against it, and only in the case they match, the exception is caught. We can chain multiple handlers (catch expressions), each one with a different parameter type. Only the handler that matches its type with the argument specified in the throw statement is executed. If we use an ellipsis (...) as the parameter of catch, that handler will catch any exception no matter what the type of the throw exception is. This can be used as a default handler that catches all exceptions not caught by other handlers if it is specified at last: try { // code here } catch (int param) { cout << "int exception"; } catch (char param) { cout << "char exception"; } catch (...) { cout << "default exception"; }

In this case the last handler would catch any exception thrown with any parameter that is neither an int nor a char. After an exception has been handled the program execution resumes after the try-catch block, not after the throw statement. It is also possible to nest try-catch blocks within more external try blocks. In these cases, we have the possibility that an internal catch block forwards the exception to its external level. This is done with the expression throw; with no arguments. For example: try { try { // code here } catch (int n) { throw; } } catch (...) { cout << "Exception occurred"; } Q5 Discuss the various STL components in brief. [ 5 Marks ] A5 Below is the list of STL Components: 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 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. Iterators Iterators are like locations 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 cab be used as a location specifier for a file. Algorithms The STL algorithms are template C++ functions to perform operations on container. In order to be able to work with many different types of container, 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.

Functions 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. Q6 Describe the time overhead of operations on sequence containers. [ 5 Marks ] A6 To choose a container, we need to decide what sort of operations we will most frequently perform on our data. And then we can use the following table. Operation Vector Access first constant element Access last constant element Access random constant element Add/delete at Linear beginning Add/delete at end constant Add/delete at Linear random Deque constant constant constant constant constant linear List constant constant linear constant constant constant

Q7 Discuss how object diagrams are different from class diagram. [ 5 Marks ] A7 A class diagram is a graph of Classifier elements connected by their various static relationships. Note that a class diagram may also contain interfaces, packages, relationships, and even instances, such as objects and links. Perhaps a better name would be static structural diagram, but class diagram is shorter and well established. An object diagram is a graph of instances, including objects and data values. A static object diagram is an instance of a class diagram; it shows a snapshot of the detailed state of a system at a point in time. The use of object diagrams is fairly limited, mainly to show examples of data structures. Tools need not support a separate format for object diagrams. Class diagrams can contain objects, so a class diagram with objects and no classes is an object diagram. The phrase is useful, however, to characterize a particular usage achievable in various ways. The basic idea is that class diagrams focus on classes and object diagrams focus on objects, but it is possible to mix classes and objects on the same diagram for various purposes, so the separation is not rigid. Class

diagrams show the logical, static structure of a system and are central the Unified Modeling Language. Object diagrams play a smaller role in UML. They are used primarily for documenting test cases and scenarios, and for discussing examples.

You might also like