Object Oriented Programming 2017-18 Previous Year Paper Solution
Long Questions

Q3 a) Explain the following concepts of object oriented programming in detail with an example. [Marks: 10]

i) Data abstraction

ii) Inheritance

iii) Polymorphism

iv) Objects

Ans: Data abstraction

Data abstraction is a programming and design technique that refers to providing only essential details to the outside world and hiding their implementation details. For example,

A music system, which we can turn on and off, change the song, adjust the volume, can connect to mobile using Bluetooth, etc, but we don’t know its internal implementation details how it works.

In C++, classes provide data abstraction using access specifiers(public, private, etc.)

C++ Data Abstraction Code Example:

#include <iostream>
using namespace std;

class Account {
   public:
      // constructor
      Account(double amt= 0) {
         balance = amt;
      }
      
      // interface to outside world
      void addMoney(double amt) {
         balance += amt;
      }
      
      // interface to outside world
      int getBalance() {
         return balance ;
      };
      
   private:
      // hidden data from outside world
      int balance;
};

int main() {
   Account a;
   
   a.addMoney(2000);
   a.addMoney(1000);
   a.addMoney(4000);

   cout << "Balance : " << a.getBalance() <<endl;
   return 0;
}

The public members – addMoney and getBalance are the interfaces to the outside world and a user needs to know them to use the class. The private member balance is something that the user doesn’t need to know about, but is needed for the class to operate properly.

Inheritance:

Inheritance is one of the key features of Object-oriented programming language C++. It allows users to create a new class called derived class from an existing class called a base class.

The derived class inherits all the features from the base class and can have additional features of its own.

Syntax of Inheritance:

class parent_class
{
    //Body of parent class
};
class child_class : access_modifier parent_class
{
   //Body of child class
};

Inheritance Code Example:

#include <iostream>
using namespace std;

class Student {
public:
  Teacher(){
    cout<<"I am a Studnet Object"<<endl;
  }
  string UniversityName = "BPUT";
};
//This class inherits Teacher class
class BtechStudent : public Student {
public:
  BtechStudnet(){
    cout<<"I am a Btech Student Object"<<endl;
  }
  int NoOfSemester = 8;
  string name = "Ajay";
};
int main() {
  BtechStudent std;
  cout<<"Name: "<<std.name<<endl;
  cout<<"UniversityName Name: "<<std.UniversityName <<endl;
  cout<<"NoOfSemester : "<<std.NoOfSemester <<endl;
  return 0;
}

Polymorphism:

Polymorphism means having many forms. Polymorphism is a key feature of object oriented programming that allows the object to perform different tasks.

There are two types of polymorphism in C++:

  1. Compile time polymorphism(ex: Operator Overloading, Function Overloading)
  2. Runtime polymorphism (ex: Virtual Function)

Compile Time Polymorphism

This is also know as Static Polymorphism. Function overloading is an example of Static Polymorphism. In overloading, the function has a same name but different signatures.It is also known as Compile Time Polymorphism because the decision of which method is to be called is made at compile time.

Runtime Polymorphism

Runtime polymorphism is also known as late binding.  Here, the method name and the method signature. Virtual Function is an example of runtime polymorphism.

Objects:

Objects are a key element of object-oriented programming.

OBJECT is an instance of a class. An object is nothing but a self-contained component which consists of methods and properties to make a particular type of data useful.

When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. To use the data and access functions defined in the class, you need to create objects.

Syntax to Create Object in C++

className objectName;

b) Write a c++ program to find the largest number among 10 elements in an array. [Marks: 5]

Ans: C++ program code:

#include <iostream>
using namespace std;

int main()
{
    int i, n;
    float arr[10];

    cout << "Enter 10 number of elements: ";
    // Store number entered by the user in the array
    for(i = 0; i < 10; ++i)
    {
       cin >> arr[i];
    }

    // Loop to find the largest number 
    for(i = 1;i < n; ++i)
    {
       if(arr[0] < arr[i])
           arr[0] = arr[i];
    }
    cout << "Largest element is : " << arr[0];

    return 0;
}

Q4 a) List out the rules for operator overloading. With a suitable example explain operator overloading. [Marks: 10]

Ans: Rules for operator overloading:

  1. we can overload unary operator as only unary operator, it cannot be overload as binary operator and vice-versa.
  2. We cannot overload those operators that are not available in C++ like ‘$’.
  3. We can perform operator overloading in only user defined classes. We cannot change the operators existing functionality.
  4. we cannot change the presidency and associativity of operators.
  5. There are some operators cannot be overloaded, for example: ternary operator(?:), Scope resolution operator(::),pointer to member operator(.*) etc.

Operator Overloading:

The meaning of an operator(+,-, etc) is always same for variable of basic data types like: int, double etc. For example: To add two integers, + operator is used.

However, for user-defined types (like objects), we can redefine the way the operator works. For example + operator can be redefined and can be used to concatenate or doing any other operations. This is known as operator overloading in c++.

C++ Operator Overloading Code Example:

#include<iostream> 
using namespace std; 
  
class Complex { 
private: 
    int real, imag; 
public: 
    Complex(int r = 0, int i =0)  {real = r;   imag = i;} 
      
    // This is automatically called when '+' is used with 
    // between two Complex objects 
    Complex operator + (Complex const &obj) { 
         Complex res; 
         res.real = real + obj.real; 
         res.imag = imag + obj.imag; 
         return res; 
    } 
    void print() { cout << real << " + i" << imag << endl; } 
}; 
  
int main() 
{ 
    Complex c1(10, 5), c2(2, 4); 
    Complex c3 = c1 + c2; // An example call to "operator+" 
    c3.print(); 
} 

b) Explain copy constructor with suitable C++ coding. [Marks: 5]

Ans: A Copy constructor is an overloaded constructor used to declare and initialize an object from another object.

It is used to create an object, hence it is called a constructor. And, it creates a new object, which is exact copy of the existing copy, hence it is called copy constructor.

Syntax:

Class_name(const class_name &old_object)
{
    . . . .
}

Sample Program to demonstrate Copy Constructor:

#include <iostream>  
using namespace std;  
class Demo  
{  
   public:  
    int num1, num2;  
    /* parameterized constructor */
    Demo(int a,int b)   
    {  
      num1=a;  
      num2=b;
    }  
    /* Copy constructor */
    Demo(Demo &obj)  
    {  
        num1 = obj.num1; 
        num2 = obj.num2; 
    }  
};  
int main()  
{  
  Demo object1(10,20);               // Calling the parameterized constructor.  
  Demo object2(a1);                //  Calling the copy constructor.  
  cout<<object2.num1;  
  cout<<object2.num2;
  return 0;  
}  

Q5 a) Differentiate between static binding and dynamic binding. Explain each mechanism with suitable examples. [Marks: 10]

Ans: Difference between static binding and dynamic binding:

Static Binding Dynamic Binding
1. Static binding occurs during compile time2. Dynamic binding occurs during runtime.
2. Static binding uses Type (class in c++) information for binding. 2. Dynamic binding uses object to resolve binding.
3. Overloaded methods are bonded using static binding.3. Overridden methods are bonded using dynamic binding at runtime.

Binding refers to the process of converting identifiers such as variable into addresses. It takes place either at compile time or at runtime

Static Binding Example:

// C++ program to demonstrate the example of static binding
#include <iostream>
using namespace std;

class ComputeAvg
{
	public:

	int Avg(int x, int y)
	{
		return (x + y)/2;
	}

	int Avg(int x, int y, int z)
	{
		return (x + y + z)/3;
	}
};

int main()
{
	ComputeAvg obj;
	cout << "Avg is " << obj.Avg(110, 120) << '\n';
	cout << "Avg is " << obj.Avg(110, 60, 20) << '\n';

	return 0;
}

Here Avg() function is overloaded to accept two or three arguments. Even though there are two functions with the same name inside the ComputeAvg class, the function call to Avg() binds to the correct function depending on the parameters passed. This binding is done during compile time called static binding.

Dynamic Binding Example:

// C++ program to demonstrate the example of dynamic binding
#include <iostream>
using namespace std;

class Base
{
	public:

	// Virtual function
	virtual void Display()
	{
		cout << "Hey, I am Base Class.\n";
	}
};

class Derived: public Base
{
	public:
	void Display()
	{
		cout << "Hey, I am Derived class.\n";
	}
};

int main()
{
	Base base;
	Derived derived;

	Base *Ptr = &base;
	Ptr->Display();

	Ptr = &derived;
	Ptr->Display();

	return 0;
}

Consider the above code where we have a base class and derived class. Base class has a virtual method Display() which is overridden by derived class.

Now, consider the main function where the decision to which class’s function will be invoked depends on the dynamic type of the object pointed to by Ptr, and this information only available at the runtime and this is known as dynamic binding.

b) Explain inline function in C++. [Marks: 5]

Ans: The inline functions are a C++ enhancement feature to increase the execution time of a program.  Inline functions are actual functions, which are copied everywhere during compilation, like preprocessor macro, so the overhead of function calling is reduced.  For example,

inline int function_name(int num) 
{ 
    return num*num; 
}

Example Code:

#include <iostream> 
using namespace std; 
inline int square(int num) 
{ 
     return num*num; 
} 
inline int increment(int num) 
{ 
     return ++num; 
}
int main() 
{ 
     int x = 10;
     cout << "The square of 5 is: " << square(5) << "n"; 
     cout << "Incrementing x " << increment(x) << "n";
     return 0; 
} 

Q6 a) What do you mean by virtual function? Differentiate it from pure virtual functions with examples. [Marks: 10]

Ans: Virtual Function:

A virtual function is a member function in the base class that expects to be redefined in derived classes.

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.

Example Code:

Class Base
{
   int a;
   public:
       Base()
       {
          a = 1;
       }
       virtual void show()
       {
          cout <<"I am Base class";
       }
};

Class Derived: public Base
{
   int b;
   public:
       Derived()
       {
          b = 2;
       }
       virtual void show()
       {
          cout <<"I am Derived";
       }
};

int main()
{
   Base *pBase;
   Derived derObj;
   pBase = &derObj;
   pBase->show();
   return 0;
}

Output: Output is “I am Derived” since pBase points to object of Derived class and show() is virtual in base class Base.

Difference between Virtual Function and Pure Virtual Function

Virtual FunctionPure Virtual Function
1. A virtual function has its definition in the base class
Example:
virtual funct_name(parameter_list)
{
// Body
}
1. Pure virtual functions don’t have any definition in the base class.
Example:
virtual funct_name(parameter_list)=0;
2. All the derived classes may or may not redefine the virtual function definition of the base class2. All derived classes must override the virtual function of the base class
3. An abstract class is not possible3. If a class contains at least one pure virtual function then it is abstract

b) Write a C++ program to read from 2 files simultaneously. [Marks: 5]

Ans: C+ program code:

#include <iostrem.h>
#include <fstream.h>
#include <stdlib.h>

int main ()
{
                        const int SIZE=80;
                        char line [SIZE];
                        ifstream fin1, fin2;
                        fin1.open ("country");
                        fin2.open ("capital");
                        for (int i=1; i<10; i++)
                        {
                                    if (fin1.eof ()! =0)
                                    {
                                     cout<<"Exit from country \n";
                                    exit (1);
                                    }
                                    fin1.getline (line, SIZE);
                                    cout<<"Capital of"<<line;
                                    if (fin2.eof ()! =0)
                                    {
                                                cout<<"Exit from capital\n";
                                                exit (1);
                                    }
                                    fin2.getline (line, SIZE);
                                    cout<<line<<"\n";
                       }
            return 0;
}

Q7 a) Define polymorphism. Explain the different types of polymorphism and its advantages. [Marks: 10]

Ans:

Polymorphism:

Polymorphism means having many forms. Polymorphism is a key feature of object oriented programming that allows the object to perform different tasks.

There are two types of polymorphism in C++:

  1. Compile time polymorphism(ex: Operator Overloading, Function Overloading)
  2. Runtime polymorphism (ex: Virtual Function)

Compile Time Polymorphism

This is also know as Static Polymorphism. Function overloading is an example of Static Polymorphism. In overloading, the function has a same name but different signatures.It is also known as Compile Time Polymorphism because the decision of which method is to be called is made at compile time.

Runtime Polymorphism

Runtime polymorphism is also known as late binding.  Here, the method name and the method signature. Virtual Function is an example of runtime polymorphism.

Advantages of Polymorphism

There are many advantage of Polymorphism:

  1. Method overloading allows methods that perform similar or closely related functions to be accessed through a common name. For example, a program performs operations on an array of numbers which can be int, float, or double type. Method overloading allows you to define three methods with the same name and different types of parameters to handle the array operations.
  2. Method overloading can be implemented on constructors allowing different ways to initialize objects of a class. This enables you to define multiple constructors for handling different types of initialization.
  3. Method overriding allows a subclass to use all the general definitions that a superclass provides and adds specialized definitions through overridden methods.
  4. Method overriding works together with inheritance to enable code-reuse of existing classes without the need for re-compilation.

b) Describe virtual function with suitable example. [Marks: 5]

Ans:

Virtual Function:

A virtual function is a member function in the base class that expects to be redefined in derived classes.

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.

Example Code:

Class Base
{
   int a;
   public:
       Base()
       {
          a = 1;
       }
       virtual void show()
       {
          cout <<"I am Base class";
       }
};

Class Derived: public Base
{
   int b;
   public:
       Derived()
       {
          b = 2;
       }
       virtual void show()
       {
          cout <<"I am Derived";
       }
};

int main()
{
   Base *pBase;
   Derived derObj;
   pBase = &derObj;
   pBase->show();
   return 0;
}

Q8 a) Explain different types of inheritance concepts with suitable examples and diagrams. [Marks: 10]

Ans: Inheritance

It is one of the most significant features of object-oriented programming. It is nothing but the ability of a class to inherit all the characteristics of another class.

Types of Inheritance in C++

There are basically 5 types of inheritance in C++.

  1. Single Inheritance
  2. Multiple Inheritance
  3. Hierarchical Inheritance
  4. Multilevel Inheritance
  5. Hybrid Inheritance

Single Inheritance

When a class extends another one class only then we call it a single inheritance. We can represent diagrammatically it as shown below:

Single Inheritance

Here class B extends only one class which is A.

Example Code: Single Inheritance

Class Base
{
   public void DisplayBase()
   {
     cout<<"I am Base Method"<<endl;
   }
}

Class Derived extends Base
{
   public void DisplayDerived()
   {
     cout<<"I am Derived Method"<<endl;
   }
   public static void main(String args[])
   {
     Derived  obj = new Derived ();
     obj.DisplayBase(); //calling base class method
     obj.DisplayDerived(); //calling local method
  }
}

Multiple Inheritance

Multiple Inheritance happens when the derived class inherits its properties from more than one base class. We can represent diagrammatically it as shown below:

Example Code: Multiple Inheritance

#include<iostream> 
using namespace std;
class Base1
{
    public:
    int a=10;
    void DisplayBase1()
    {
        cout<<"I am Base1"<<endl;
    }
};
class Base2
{
    public:
    int b = 20;
    void DisplayBase2()
    {
        cout<<"I am Base2"<<endl;
    }
};
class Derived: public Base1, public Base2 //derived class from classes    // Base1 and Base2
{
public:
    int c = 30;
    void Display()
    {
        cout<<"A : " << a <<endl;
        cout<<"B : " << b <<endl;
        cout<<"C : " << b <<endl;
    }
};
int main()
{
    cout<<"Multiple Inheritance Demo"<<endl;
    Derived der; 
    der.Display();
    return 0;
}

b) Write a C++ program that will give the conditions of environment required, food habits and unique characteristics of pet animals fish and dog. Define a base called pet that describe any common household pet, two derived classes called fish and dog with items specific to that type of animals. Write pure virtual functions in the base class for operations that are common to both types of animals. Write a program to test the usage of classes. [Marks: 5]

Ans:

Q9 a) Discuss the need for execution with try, catch and throw keywords and draw the exception handling model. [Marks: 10]

Ans:

b) What is class template? Write the syntax for class template. Write an example program for class template. [Marks: 5]

Ans: Templates are the mechanism by which C++ implements the generic concept. Simply, they allow you to pass data type as a parameter so that you don’t need to write the same code for different data types.

Class Template:

A class template provides a specification for generating classes based on parameters.

Syntax for class template:

template <class T>
class className
{
   ... .. ...
public:
   T var;
   T someOperation(T arg);
   ... .. ...
};

T is the template argument which is a placeholder for the data type used.

A Calculator c++ program:

#include <iostream>
using namespace std;

template <class T>
class Calculator
{
private:
	T num1, num2;
	
public:
	Calculator(T n1, T n2)
	{
		num1 = n1;
		num2 = n2;
	}
	
	void displayResult()
	{
		cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
		cout << "Addition is: " << add() << endl;
		cout << "Subtraction is: " << subtract() << endl;
		cout << "Product is: " << multiply() << endl;
		cout << "Division is: " << divide() << endl;
	}
	
	T add() { return num1 + num2; }
	
	T subtract() { return num1 - num2; }
	
	T multiply() { return num1 * num2; }
	
	T divide() { return num1 / num2; }
};

int main()
{
	Calculator<int> intCalc(5, 1o);
	Calculator<double> doubleCalc(6.5, 5.1);
	
	cout << "Int results:" << endl;
	intCalc.displayResult();
	
	cout << endl << "Float results:" << endl;
	doubleCalc.displayResult();
	
	return 0;
}