Introduction To Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

(2½ Hours) [Total Marks: 75]

Subject: OOPs with C++

Solution Set

1. Attempt any three of the following: 15


a. What is object oriented programming? State its applications.

Ans: Object-oriented programming (OOP) is a software programming


modelconstructed around objects. This model compartmentalizes data into objects
(data fields) and describes object contents and behavior through the declaration of
classes (methods). Object-oriented programming allows for simplified programming.
Its benefits include reusability, refactoring, extensibility, maintenance and efficiency.
Applications:

• Real-time system
• Simulation and modeling
• Object-oriented data bases
• Hypertext, Hypermedia, and expertext
• AI and expert systems
• Neural networks and parallel programming
• Decision support and office automation systems
• CIM/CAM/CAD systems

b. Illustrate the relationship between object and class.


Ans:
objects contain data, and code to manipulate that data. The entire set of data and code
of an object can be made a user-defined data type with the help of class. Each object is
associated with the data of type class with which they are created. A class is thus a
collection of objects similar types. For examples, Mango, Apple and orange members
of class fruit.
c. Explain the concept of abstraction with suitable example.
Ans: Abstraction refers to the act of representing essential features without including
the background details or explanation. Classes use the concept of abstraction and are
defined as a list of abstract attributes such as size, wait, and cost, and function operate
on these attributes. They encapsulate all the essential properties of the object that are to
be created. The attributes are sometime called data members because they hold
information. The functions that operate on these data are sometimes called methods or
member function.
d. Explain in brief about reusability with suitable example.
Ans: Inheritance ( Reusability) is the process by which objects of one class acquired
the properties of objects of another classes. It supports the concept of hierarchical
classification. For example, the bird, ‘robin’ is a part of class ‘flying bird’ which is
again a part of the class ‘bird’.
e. What is polymorphism? Give suitable example for the same.
Ans: Polymorphism means the ability to take more than on form. An operation may
exhibit different behavior is different instances. The behavior depends upon the types
of data used in the operation. For example, consider the operation of addition. For two
numbers, the operation will generate a sum. If the operands are strings, then the
operation would produce a third string by concatenation. The process of making an
operator to exhibit different behaviors in different instances is known as operator
overloading.
f. Write a note on dynamic binding.
Ans: Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given
procedure call is not known until the time of the call at run time. It is associated with
polymorphism and inheritance. A function call associated with a polymorphic
reference depends on the dynamic type of that reference.

2. Attempt any three of the following: 15


a. Explain the structure of C++ class.
Ans:
Class MyClass
{
private: datatype var;
public:
void Method1()
{ Define Method // }
};
void main()
{ MyClassobj;
Obj.Method1();
}

b. Write a C++ program to create a class Bank with { acno, custname, bal} as its
attributes. And implement the methods withdraw() , deposit() and showBalance().
Class Bank
{
private: intaccno; char custname[40];double bal;
public:
void withdraw()
{ Define Method // }
void deposit()
{ Define Method // }
void showBalance()
{ Define Method // }
};
void main()
{ Bank obj;
obj.withdraw(); obj.deposit(); obj.showBalance();
}

c. Explain in brief the concept of friend function and class with suitable example.
lass Box {
double width;

public:
friend void printWidth( Box box );
void setWidth( double wid );
};

// Member function definition


void Box::setWidth( double wid ) {
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout<< "Width of box : " <<box.width<<endl;
}

// Main function for the program


int main() {
Box box;

// set box width without member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}
d. What is constructor? State its characteristics.
A constructor (having the same name as that of the class) is a member function which
is automatically used to initialize the objects of the class type with legal initial values.
These have some special characteristics. These are given below:
(i) These are called automatically when the objects are created.
(ii) All objects of the class having a constructor are initialized before some use.
(iii) These should be declared in the public section for availability to all the functions.
(iv) Return type (not even void) cannot be specified for constructors.
(v) These cannot be inherited, but a derived class can call the base class constructor.
(vi) These cannot be static.
(vii) Default and copy constructors are generated by the compiler wherever required.
Generated constructors are public.
(viii) These can have default arguments as other C++ functions.
(ix) A constructor can call member functions of its class.
(x) An object of a class with a constructor cannot be used as a member of a union.
(xi) A constructor can call member functions of its class.
(xii) We can use a constructor to create new objects of its class type by using the
syntax

e. Write a C++ program to implement the concept of constructor and destructor.


class add
{
private :
int num1,num2,num3;
public :
add(int=0, int=0); //default argument constructor
//to reduce the number of constructors
void sum();
void display();
~ add(void); //Destructor
};
Add:: ~add(void)
{
Num1=num2=num3=0;
Cout<<”\nAfter the final execution, me, the object has entered in the”
<<”\ndestructor to destroy myself\n”;
}
//Constructor definition add()
Add::add(int n1,int n2)
{
num1=n1;
num2=n2;
num3=0;
}
//function definition sum ()
Void add::sum()
{
num3=num1+num2;
}
//function definition display ()
Void add::display ()
{
cout<<”\nThe sum of two numbers is “<<num3<<end1;
}
void main()
{
Add obj1,obj2(5),obj3(10,20): Obj1.sum(); //function call
Obj2.sum();
Obj3.sum();
cout<<”\nUsing obj1 \n”;
obj1.display(); //function call
cout<<”\nUsing obj2 \n”;
obj2.display();
cout<<”\nUsing obj3 \n”;
obj3.display();
}
f. Explain the concept of pointer to object with suitable example.
Ans: A variable that holds an address value is called a pointer variable or simply
pointer.
Pointer can point to objects as well as to simple data types and arrays.
sometimes we dont know, at the time that we write the program , how many objects we
want to create. when this is the case we can use new to creat objects while the
program is running. new returns a pointer to an unnamed objects.
class student
{
private:
introllno;
string name;
public:
student():rollno(0),name("")
{}
student(int r, string n): rollno(r),name (n)
{}
void get()
{
cout<<"enter roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
}
void print()
{
cout<<"roll no is "<<rollno;
cout<<"name is "<<name;
}
};
void main ()
{
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
}

3. Attempt any three of the following: 15


a. Explain the concept of function overloading with suitable example.
long add(long, long);
float add(float, float);

int main()
{
long a, b, x;
float c, d, y;

cout<< "Enter two integers\n";


cin>> a >> b;

x = add(a, b);

cout<< "Sum of integers: " << x <<endl;

cout<< "Enter two floating point numbers\n";


cin>> c >> d;

y = add(c, d);

cout<< "Sum of floats: " << y <<endl;


return 0;
}

long add(long x, long y)


{
long sum;

sum = x + y;

return sum;
}

float add(float x, float y)


{
float sum;

sum = x + y;

return sum;
}

b. Write a C++ program to overload binary (++) operator.


Ans:
#include<iostream>
usingnamespacestd;

classBox{
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box

public:

doublegetVolume(void){
return length * breadth * height;
}

voidsetLength(doublelen){
length =len;
}

voidsetBreadth(doublebre){
breadth =bre;
}

voidsetHeight(doublehei){
height =hei;
}

// Overload + operator to add two Box objects.


Boxoperator+(constBox& b){
Boxbox;
box.length=this->length +b.length;
box.breadth=this->breadth +b.breadth;
box.height=this->height +b.height;
return box;
}
};

// Main function for the program


int main(){
BoxBox1;// Declare Box1 of type Box
BoxBox2;// Declare Box2 of type Box
BoxBox3;// Declare Box3 of type Box
double volume =0.0;// Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume =Box1.getVolume();
cout<<"Volume of Box1 : "<< volume <<endl;

// volume of box 2
volume =Box2.getVolume();
cout<<"Volume of Box2 : "<< volume <<endl;

// Add two object as follows:


Box3=Box1+Box2;

// volume of box 3
volume =Box3.getVolume();
cout<<"Volume of Box3 : "<< volume <<endl;

return0;
}

c. List the operators that cannot be overloaded. Explain the rules for overloading the
operators.
Ans:
Operators that cannot be overloaded::: , .*, . , ?:
Rules:
1. Only existing operators can be overloaded. New operators cannot be overloaded.
2. The overloaded operator must have at least one operand that is of user defined type.

3. We cannot change the basic meaning of an operator. That is to say, We cannot


redefine the plus(+) operator to subtract one value from the other.

4. Overloaded operators follow the syntax rules of the original operators. They cannot
be overridden.

5. There are some operators that cannot be overloaded like size of operator(sizeof),
membership operator(.), pointer to member operator(.*), scope resolution operator(::),
conditional operators(?:) etc

6. We cannot use “friend” functions to overload certain operators.However, member


function can be used to overload them. Friend Functions can not be used with
assignment operator(=), function call operator(()), subscripting operator([]), class
member access operator(->) etc.

7. Unary operators, overloaded by means of a member function, take no explicit


arguments and return no explicit values, but, those overloaded by means of a friend
function, take one reference argument (the object of the relevent class).

8. Binary operators overloaded through a member function take one explicit argument
and those which are overloaded through a friend function take two explicit arguments.

9. When using binary operators overloaded through a member function, the left hand
operand must be an object of the relevant class.

10. Binary arithmetic operators such as +,-,* and / must explicitly return a value. They
must not attempt to change their own arguments.

d. What is static function? Explain how it is implemented.

Ans: When we declare a member of a class as static it means no matter how many
objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero
when the first object is created, if no other initialization is present. We can't put it in
the class definition but it can be initialized outside the class as done in the following
example by redeclaring the static variable, using the scope resolution operator :: to
identify which class it belongs to.

( You can assume any program)

classBox{
public:
staticintobjectCount;

// Constructor definition
Box(double l =2.0,double b =2.0,double h =2.0){
cout<<"Constructor called."<<endl;
length = l;
breadth = b;
height = h;

// Increase every time object is created


objectCount++;
}
doubleVolume(){
return length * breadth * height;
}
staticintgetCount(){
returnobjectCount;
}

private:
double length;// Length of a box
double breadth;// Breadth of a box
double height;// Height of a box
};

// Initialize static member of class Box


intBox::objectCount=0;

int main(void){
// Print total number of objects before creating object.
cout<<"Inital Stage Count: "<<Box::getCount()<<endl;

BoxBox1(3.3,1.2,1.5);// Declare box1


BoxBox2(8.5,6.0,2.0);// Declare box2

// Print total number of objects after creating object.


cout<<"Final Stage Count: "<<Box::getCount()<<endl;

return0;
}

e. What is pure virtual function? Explain how it is implemented.


Ans: Pure virtual Functions are virtual functions with no definition. They start with
virtual keyword and ends with = 0. Here is the syntax for a pure virtual function,
virtual void f() = 0;
class Base //Abstract base class
{
public:
virtual void show() = 0; //Pure Virtual Function
};

class Derived:public Base


{
public:
void show()
{ cout<< "Implementation of Virtual Function in Derived class"; }
};
int main()
{
Base obj; //Compile Time Error
Base *b;
Derived d;
b = &d;
b->show();
}

• Pure Virtual functions can be given a small definition in the Abstract class,
which you want all the derived classes to have. Still you cannot create object of
Abstract class.
• Also, the Pure Virtual function must be defined outside the class definition. If
you will define it inside the class definition, complier will give an error. Inline
pure virtual definition is Illegal.

f. Explain in brief the concept of abstract class.


Ans: Abstract Class is a class which contains atleast one Pure Virtual function in it.
Abstract classes are used to provide an Interface for its sub classes. Classes inheriting
an Abstract Class must provide definition to the pure virtual function, otherwise they
will also become abstract class.

Characteristics of Abstract Class

1. Abstract class cannot be instantiated, but pointers and refrences of Abstract


class type can be created.
2. Abstract class can have normal functions and variables along with a pure
virtual function.
3. Abstract classes are mainly used for Upcasting, so that its derived classes can
use its interface.
4. Classes inheriting an Abstract Class must implement all pure virtual functions,
or else they will become Abstract too.

4. Attempt any three of the following: 15


a. Explain the concept of multilevel inheritances with suitable example.
Ans:

In this type of inheritance the derived class inherits from a class, which in turn inherits
from some other class. The Super class for one, is sub class for the other.
b. Write a C++ program to implement the following hierarchy of inheritance.
Lion Tiger

Animal

Ans:
Class Lion
{
};
Class Tiger
{
};
Class Animal : public Lion , Tiger
{
};

c. Explain the concept of method overriding with suitable example.


C++ Function Overriding. If derived class defines same function as defined in its
base class, it is known as function overriding in C++. It is used to achieve runtime
polymorphism. It enables you to provide specific implementation of the function
which is already provided by its base class.
d. Write a note on containership.
When a class contains objects of another class or its members, this kind of
relationship is called containership or nesting and the class which contains objects of
another class as its members is called as container class.
Class class_name1
{
——–
——–
};
Class class_name2
{
——–
———
};
Class class_name3
{
Class_name1 obj1; // object of class_name1
Class_name2 obj2; // object of class_name2
———-
———–
};

e. Explain the mechanism of handling the exception with suitable example.


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.
try {
// protected code
} catch( ExceptionName e1 ) {
// catch block
} catch( ExceptionName e2 ) {
// catch block
} catch( ExceptionNameeN ) {
// catch block
}

f. Explain in brief about hybrid inheritance with suitable example.

Ans: Hybrid Inheritance is combination of Hierarchical and Multilevel Inheritance.

5. Attempt any three of the following: 15


a. Explain the concept of function template with suitable example.

Ans: Function Template

The general form of a template function definition is shown here −

template <class type> ret-type func-name(parameter list) {


// body of function
}
#include <iostream>
#include <string>

using namespace std;

template <typename T>


inline T const& Max (T const& a, T const& b) {
return a < b ? b:a;
}

int main () {
inti = 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;
}

b. Write a C++ program to implement the concept of class template.


Ans:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>

using namespace std;

template <class T>


class Stack {
private:
vector<T>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 <class T>


void Stack<T>::push (T const&elem) {
// append copy of passed element
elems.push_back(elem);
}

template <class T>


void Stack<T>::pop () {
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}

// remove last element


elems.pop_back();
}

template <class T>


T Stack<T>::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<int>intStack; // stack of ints
Stack<string>stringStack; // stack of strings

// manipulate int stack


intStack.push(7);
cout<<intStack.top() <<endl;

// manipulate string stack


stringStack.push("hello");
cout<<stringStack.top() <<std::endl;
stringStack.pop();
stringStack.pop();
} catch (exception const& ex) {
cerr<< "Exception: " <<ex.what() <<endl;
return -1;
}
}

c. State and explain different file modes.


Ans:

The mode parameter specifies the mode in which the file has to be opened.

d. Write a C++ program to read the input from the user and write into the file. [Select a
suitable file mode]
#include <fstream>
#include <iostream>
#include <string>

usingnamespacestd;

int main()
{
string sentence;
string mysent;

//Creates an instance of ofstream, and opens example.txt


ofstreama_file ( "example.txt", ios::app );
cin>>mysent;
// Outputs to example.txt through a_file
a_file<<mysent<< "\n";
// Close the file stream explicitly
a_file.close();
//Opens for reading the file
ifstreamb_file ( "example.txt" );
//Reads one string from the file
b_file>>mysent;
cout<< "Please Write the sentence:" <<"
<<"\n";
cin>> sentence;
if (sentence == mysent)
{
cout<< "you did it right!" << "\n";
"
}
else
{
cout<< "No!" <<endl;
}
system("pause"); // wait for a keypress
// b_file is closed here
}

e. Write a C++ program to display the contents from the file in a console mode. [Select a
suitable file mode]
#include <stdio.h>
#include <stdlib.h> // For exit()

intmain()
{
FILE*fptr;

charfilename[100], c;

printf("Enter the filename to open \n");


scanf("%s", filename);

// Open file
fptr = fopen(filename, "r");
if(fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}

// Read contents from file


c = fgetc(fptr);
while(c != EOF)
{
printf("%c", c);
c = fgetc(fptr);
}

fclose(fptr);
return0;
}

f. Write a C++ program to copy the contents from one file to other file. [Select a suitable
file mode]
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
void main()
{
ofstreamfout;
ifstream fin;
inti=0;
int n;
char ch[20];
clrscr();
fout.open("a.txt");
cout<<"enter no. of lines";
cin>>n;
cout<<"\nenter contents to first file\n\n";
do
{
cin.getline(ch,20);
fout<<ch;
fout<<"\n";
i++;
}while(i<=n);
fout.close();
fin.open("a.txt");
fout.open("a.txt");
cout<<"\ncontents of second file\n";
while(fin.eof()==0)
{
fin.getline(ch,20);
fout<<ch;
fout<<"\n";
}
fout.close();
fin.close();
fin.open("a1.txt");
while(fin.eof()==0)
{
fin.getline(ch,20);
cout<<ch;
cout<<"\n";
}
fin.close();
getch();
}

_____________________________

You might also like