Nov_Dec_OOPs Solved Question Papers- 2019 Pattern (1)

You might also like

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

[5869]-249

S.E. (Electronics / E & TC/Electronics & Computer)


OBJECT ORIENTED PROGRAMMING (2019 Pattern)
(Semester - IV)
Solution With Appropriate Answers

Instruction to the candidate


1) Answer Q.1 or Q.2, Q.3 or Q.4, Q.5 or Q.6, Q.7 or Q.8.
2) Neat diagrams must be drawn wherever necessary.
3) Figures to the right indicate full marks.

Tips to Remember You Start Writing Answer Sheet


1) Read the question carefully.
2) Plan your answer before writing.
3) Start with a strong introduction.
4) Organize your thoughts in a logical manner.
5) Support your arguments with evidence and examples.
6) Use clear and concise language.
7) Be specific and precise in your responses.
8) Address all parts of the question.
9) Manage your time effectively.
10) Review and revise your answers.

These points should help you structure and write your answers
effectively during the exam. Good luck!
Q.No. TOTAL
E 1
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q. 1
 A) Definition of operator overloading :
- Operator overloading is a feature in programming languages that allows you to
redefine the behavior of certain operators (such as +, -, *, /) for custom data types
or objects.
- This assign more than one operation on an some operator known as operator
overloading.
- To achieved operator overloading we have to write a special function known as
operator().
Syntax :
Return_type operator symbol (argument list) {
Body ;
}

Rules for overloading operator:


- Only existing operators can be overloaded.
- The basic meaning of the operator can not be changed.
- Overloaded operators must follow the syntax of original operator. For example for
Binary operator operand1 operator operand2 is the syntax and this can not be
Changed during overloading.
- Overloaded operators must have at least one operand that is of user defined type.
- Binary arithmetic operators(+,-, * and /) must return a value.
- When binary operators overloaded through a member function, the left hand
Operand must be an object of relevant class.
- Binary operators overloaded through a member function must take one explicit
Argument.
- Binary operators overloaded through friend function takes two arguments.
- Unary operators overloaded through a member function must take no explicit
Argument and no return value.
- Unary operators overloaded through friend function takes one explicit argument.
Q.No. TOTAL
E 2
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
 B) C++ program to overload binary operator “+” to add, “- ” to subtract, “* ”
to multiply, “/ ” to devide and “~” to conjugate of complex number.

#include <iostream>
using namespace std;
class Complex {
int x, y;
public:
void read() {
cout << "Enter the real and imaginary parts of a complex number:";
cin >> x >> y;
}
Complex operator+(Complex c) {
Complex c1;
c1.x = x + c.x;
c1.y = y + c.y;
return c1;
}
Complex operator-(Complex c) {
Complex c1;
c1.x = x - c.x;
c1.y = y - c.y;
return c1;
}
Complex operator*(Complex c) {
Complex c1;
c1.x = x * c.x;

c1.y = y * c.y;
return c1;
}
Q.No. TOTAL
E 3
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
Complex operator/(Complex c) {
Complex c1;
c1.x = x / c.x;
c1.y = y / c.y;
return c1;
}
Complex operator~() {
Complex c1;
c1.x = x;
c1.y = y;
return c1;
}
void display() {
if (y < 0)
cout << x << y << "i";
else
cout << x << "+i" << y;
}
};
int main() {
Complex c1;
Complex c2;
Complex c3 ;
c1.read();
c2.read();
c3 = c1 + c2;
c3.display();
cout << endl;
c3 = c1 - c2;
c3.display();
Q.No. TOTAL
E 4
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
cout << endl;
c3 = c1 * c2;
c3.display();
cout << endl;
c3 = c1 / c2;
c3.display();
cout << endl;
c3 = ~c1;
c3.display();
return 0;
}

Output :
Enter the real and imaginary parts of a complex number:2
3
Enter the real and imaginary parts of a complex number:4
5
6+i8
-2-2i
8+i15
0.5+i0.6
2+i3

Code explanation :
- Here we have overloaded the binary operator "+" by the operator overloading
function Complex operator +(Complex c). Two objects of the class complex are
created.
- The values of these complex variables are read. The two objects of the class
"complex" are added using the same syntax of the addition operator i.e ‘+’..
- The result is returned to another object of the same class.
Q.No. TOTAL
E 5
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
 C) Definition of friend function :
- friend function is defined as a function that is granted access to the private and
protected members of a class. It is declared inside the class, but it is not a member
of the class.
- Friend functions are useful when you need to allow external functions to access
the private or protected data of a class without making them a member of the
class.
Syntax of friend function :
friend ReturnType functionName(Parameters);
friend – it is the keyword used to declare a friend function inside a class.
ReturnType- represents the data type that the friend function returns,
functionName – it is the name of the friend function,
Parameters – this are the input parameters (if any) required by the function.

C++ program that demonstrate the use of friend function :


#include <iostream>
using namespace std;
class Complex{
int x, y;
public:
void read() {
cout << "Enter the real and imaginary parts of a complex number:";
cin >> x >> y;
}
friend Complex operator+(Complex c1, Complex c2);
void display() {
if (y < 0)
cout << x << y << "i";
else
cout << x << "+i" << y;
}
Q.No. TOTAL
E 6
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
}
};
Complex operator+(Complex c1, Complex c2){
Complex c;
c.x = c1.x + c2.x;
c.y = c1.y + c2.y;
return c;
}
int main(){
Complex c1;
Complex c2;
Complex c3;
c1.read();
c2.read();
c3 = c1 + c2;
c3.display();
cout << endl;
return 0;
}

Output :
Enter the real and imaginary parts of a complex number:2
3
Enter the real and imaginary parts of a complex number:4
5
6+i8
Q.No. TOTAL
E 7
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.2
 a) Definition of operator overloading :
- Operator overloading is a feature in programming languages that allows you to
redefine the behavior of certain operators (such as +, -, *, /) for custom data types
or objects.
- This assign more than one operation on an some operator known as operator
overloading.
- To achieved operator overloading we have to write a special function known as
operator().
Syntax :
Return_type operator symbol (argument list) {
Body ;
}

Program in C++ that demonstrates how to overload three unary operators: ++


(increment), -- (decrement), and ! (logical not).

#include<iostream>
using namespace std;
class MyNumber {
private:
int number;
public:
MyNumber(int num) {
number = num;
}
// Overloading increment operator (++)
MyNumber operator++() {
number++;
return *this;
}
// Overloading decrement operator (--)
Q.No. TOTAL
E 8
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.2
// Overloading decrement operator (--)
MyNumber operator--() {
number--;
return *this;
}
// Overloading logical not operator (!)
bool operator!() {
return (number == 0);
}
void display() {
cout << "Number: " << number << endl;
}
};
int main() {
MyNumber num(5);
++num;
num.display(); // Output: Number: 6
--num;
num.display(); // Output: Number: 5
if (!num) {
cout << "Number is zero" << endl;
}
else {
cout << "Number is not zero" << endl;
}
return 0;
}
Code explanation :
- In this program, we create a class “MyNumber” that represents a number. We
define three member functions, each overloading a unary operator: “operator++” for
Q.No. TOTAL
E 9
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.2
incrementing the number, “operator--” for decrementing the number , and
“operator!” for checking if the number is zero.
- In the “main” function, we create an object of “MyNumber” class and demonstrate
the usage of the overloaded unary operators. We increment and decrement the
number using the “++” and “--” operators, respectively.
- Finally, we use the logical not “!” operator to check if the number is zero or
not.When you run the program, the output will be:

Output:
Number: 6
Number: 5
Number is not zero

 b) C++ program that demonstrates a copy constructor for a string class:


#include <iostream>
#include <cstring>
Class String {
Private:
Char* buffer;
Int size;

Public:
String(const char* text) {
Size = std::strlen(text);
Buffer = new char[size + 1];
Std::strcpy(buffer, text);
}
// Copy Constructor
String(const String& other) {
Size = other.size;
Q.No. TOTAL
E 10
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.2

Buffer = new char[size + 1];


Std::strcpy(buffer, other.buffer);
}

~String() {
Delete[] buffer;
}

Void display() {
Std::cout << “String: “ << buffer << std::endl;
}
};
Int main() {
String original(“Hello, World!”);
String copy(original);
Original.display();
Copy.display();

Return 0;
}

Code explanation :
In this program, we define a String class that represents a string. The class
has a private member variable buffer of type char* that stores the string data, and
an int member variable size that represents the size of the string.
In the main function, we create an instance of the String class called original,
passing a string literal “Hello, World!” to the constructor. We then create another
String object called copy and initialize it with the original object, which invokes the
copy constructor.
Q.No. TOTAL
E 11
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.2
Output :
String: Hello, World!
String: Hello, World!

 C) Differentiate friend function with member function of the class.


Q.No. TOTAL
E 12
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.3
 a) Containment :
- Containment, also known as composition or aggregation, involves one class
containing an instance of another class as a member.
- The containing class has ownership and control over the contained object, and it
can access and manipulate the contained object's members.
- Containment allows for building complex objects by combining simpler objects.
Example:
class Engine {
// Engine class definition
};
class Car {
Engine engine; // Contained object
// Car class definition
};
In this example, the Car class contains an instance of the Engine class as a
member. The Car class has ownership and control over the Engine object, and it
can access and use its functionality.

definition of Inheritance :
The capability of the class to derive the properties and characteristic from another
class is called as inheritance. In other word it is properties by which the new class
iss created by the another class .
- It is one of the important features of oops.
Sub class – the The class that inherited property from another class is called sub
class
Superclass - the class whose property are inherited by the superclass is called Super
Classical superclass is called as a base class
Example :
class Animal {
// Animal class definition
Q.No. TOTAL
E 13
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.3

};

class Dog : public Animal {


// Dog class definition
};
program explanation :
- In this example, the Dog class inherits from the Animal class. The Dog class
inherits the properties and behaviors defined in the Animal class and can add its
own specific behaviors or override inherited behaviors.

 b) Virtual Functions :
definition :
A member function in the base class which is declared using virtual keyword is
called virtual functions.
They can be redefined in the derived class.
To demonstrate the concept of virtual functions an example program is shown below
#include<iostream>
using namespace std;
class BaseClass{
public:
int var_base=1;
virtual void display(){
cout<<"1 Dispalying Base class variable var_base "<<var_base<<endl;
}
};
class DerivedClass : public BaseClass{
public:
int var_derived=2;
void display(){
Q.No. TOTAL
E 14
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.3

cout<<"2 Dispalying Base class variable var_base "<<var_base<<endl;


cout<<"2 Dispalying Derived class variable var_derived
"<<var_derived<<endl; }
};
int main(){
BaseClass * base_class_pointer;
BaseClass obj_base;
DerivedClass obj_derived;
base_class_pointer = &obj_derived;
base_class_pointer->display();
return 0;
}

Output :
2 Dispalying Base class variable var_base 1
2 Dispalying Derived class variable var_derived 2

code explanation :
- in the above code we have used the “virtual” keyword with the “display” function
of the base class to make is virtual function so when the display function is called
by using the base class pointer the display function of the derived class will run
because the base class pointer is pointing to the derived class object.

Rules of virtual function :


- They cannot be static.
- They are accessed by object pointers.
- Virtual function can be a friend off another class A
- virtual function in the base class mighty not be used If a virtual function is
defined In a base class,
- they is no necessity of redefining it in the derived class.
Q.No. TOTAL
E 15
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.3
how to achieved run time polymorphism :
- In the run-time polymorphism, the compiler doesn’t know already what will happen
at run time.
- Run time polymorphism is also called late binding. The run time polymorphism is
considered slow because function calls are decided at run time.
- Run time polymorphism can be achieved from the virtual function.
- A function that is in the parent class but redefined in the child class is called a
virtual function. “virtual” keyword is used to declare a virtual function.

 C) Function Overloading:
- Function overloading is the ability to define multiple functions with the same
name but different parameters or argument types.
- It allows a single function name to perform different tasks based on the type,
number, or order of the arguments passed to it.
Example :
class MathOperations {
public:
int add(int num1, int num2) {
return num1 + num2;
}

double add(double num1, double num2) {


return num1 + num2;
}
};

int main() {
MathOperations math;
int sum1 = math.add(2, 3); // Calls the int version of the add() func.
Q.No. TOTAL
E 16
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.3
double sum2 = math.add(2.5, 3.5); // Calls the double version of the add()
func.
return 0;
}

Output :
sum1 = 5
sum2 = 6.0

code explanation :
In this example, the MathOperations class has two add() functions with the same
name but different parameter types (int and double).The appropriate add() function
is selected based on the argument types provided during function calls. The output
of the program would be the sum of the given numbers, using the appropriate add()
function for each data type.

Function Overriding:
whenever we write function in base and derived class in such a way that function
name, parameter must be same called function overriding.
Syntax :
Class class_name { //base class
Void func() {
body ;
}
};
Class class_name : public base_class { //derived class
Void func(){
body ;
}
};
code explanation:
Q.No. TOTAL
E 17
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.3
code explanation:
- In the above code base class consist the function i.e. func() and there is other
class which is derived class it also consist same function i.e func().
- So here we override the function in base and derived class, this is actual concept
of overriding.
Q.No. TOTAL
E 18
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.4
 a) definition of Inheritance :
- The capability of the class to derive the properties and characteristic from another
class is called as inheritance. In other word it is properties by which the new class
iss created by the another class .
- It is one of the important features of oops.
- Sub class : the The class that inherited property from another class is called sub
class
- Superclass : the class whose property are inherited by the superclass is called
Super Classical superclass is called as a base class.

Types of inheritance :
- Single inheritance
- multi level
- multiple
- hybrid,
- hierarchical.

Single inheritance :
Single inheritance is a form of inheritance in object-oriented programming
where a derived class inherits properties and behaviors from a base class.
Syntax :
class DerivedClass : access_specifier BaseClass {
// Members and functions of the derived class
};
example :
Q.No. TOTAL
E 19
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.4
- In the above figure there is a class A. we inherited class B from A. we call It
single inheritance. here the class B is Inherited from class A, this is the example
of the single inheritance

Multilevel inheritance :
Multilevel inheritance is a form of inheritance in object-oriented programming
where a derived class serves as the base class for another derived class.
Sytanx :
class DerivedClass : access_specifier BaseClass1 {
// Members and functions of the derived class
};

class SubDerivedClass : access_specifier DerivedClass {


// Members and functions of the derived class
};
example :

- in the above figure there is a Class A, Class B inherited it, then one class C
came, it inherited Class B here they have did inhabitance at multiple level. We
can call it multi level inheritance.

Multiple inheritance :
Multiple inheritance is a form of inheritance in object-oriented programming
where a derived class can inherit properties and behaviors from multiple base
classes.

class DerivedClass : access_specifier BaseClass1, access_specifier BaseClass2 {


Q.No. TOTAL
E 20
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.4
syntax :
class DerivedClass : access_specifier BaseClass1, access_specifier BaseClass2 {
// Members and functions of the derived class
};

example :

in the above figure Class A and one class B and there is another Class C which is
inheriting the properties from class A and class B also. This is multiple inheritance.

Hierarchical inheritance :
- One class serves as a parent class for more than one class Hierarchical inheritance
is a form of inheritance in object-oriented programming where multiple derived
classes inherit properties and behaviors from a single base class.
- In other word One class serves as a parent class for more than one class

Syntax :
class DerivedClass1 : access_specifier BaseClass {
// Members and functions of the derived class
};

class DerivedClass2 : access_specifier BaseClass {


// Members and functions of the derived class
};
Q.No. TOTAL
E 21
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.4

For example :

- in the above example, there is class A, which is parent class for B and Also for
C. these is an hierarchical inheritance.

Hybrid Inheritance :
- Hybrid inheritance is a type of inheritance in object-oriented programming that
combines multiple forms of inheritance, such as single inheritance, multiple
inheritance, and multilevel inheritance, to create a more complex class hierarchy.
- In other word It is a combination of more than one type of inheritance

syntax :
class DerivedClass : virtual access_specifier BaseClass {
// Members and functions of the derived class
};

example :

In the above example the Class B and class C which is inherited from Class A. also
the Class D inherited the properties from Class A and Class C. it is a combination
of multiple and hierarchical inheritance. This is called hybrid inheritance.
Q.No. TOTAL
E 22
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.4
 b) Definition of polymorphism :
- poly refers to multiple and morph refers to different form Hence polymorphism
means many structure or multiple forms of the same things
Explanation with real life example :
A person at the same time can different characteristics like a man at same time
is a father, A husband , employee So the same person poses different powers in a
different situation This is a called as a polymerism.
- There are two types of polymorphism
1. Compile- time polymorphism
2. Run time polymorphism

Compile- time polymorphism


- Compile-time polymorphism is also called early binding, which means that we are
already bound to the function call and we know that this function is going to run.
- There are two types of compile-time polymorphism:
- Function Overloading
- Operator Overloading

Run time polymorphism


- In the run-time polymorphism, the compiler doesn’t know already what will happen
at run time. Run time polymorphism is also called late binding.
- The run time polymorphism is considered slow because function calls are decided
at run time. Run time polymorphism can be achieved from the virtual function.
- A function that is in the parent class but redefined in the child class is called a
virtual function. “virtual” keyword is used to declare a virtual function.

example of how you can use the virtual keyword to achieve runtime
polymorphism in C++:
#include <iostream>
using namespace std;
Q.No. TOTAL
E 23
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
class Animal {
public:
virtual void makeSound() {
cout << "Animal makes a sound" << endl;
}
};
class Cat : public Animal {
public:
void makeSound()
override {
std::cout << "Cat meows" << endl;
}
};
class Dog : public Animal {
public:
void makeSound()
override {
cout << "Dog barks" << endl;
}
};
int main() {
Animal* animal1 = new Cat();
Animal* animal2 = new Dog();
animal1->makeSound(); // Output: Cat meows
animal2->makeSound(); // Output: Dog barks
delete animal1;
delete animal2;
return 0;
}
Q.No. TOTAL
E 24
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
code explanation :
the code demonstrates runtime polymorphism in C++ using virtual functions. It
defines a base class “Animal” with a virtual function “makeSound()”. Two derived
classes, “Cat” and “Dog”, override the “makeSound()” function.
In the “main()” function, objects of “Cat” and “Dog” are accessed through base
class pointers. The “makeSound()” function is called on these pointers, and the
appropriate overridden function is executed based on the actual object type.

Output :
Cat meows
Dog barksc

 C) C++ program that demonstrate the copy constructor for employee class .
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
string name;
int age;
double salary;
public:
// Copy constructor without const
Employee(Employee& other)
: name(other.name), age(other.age), salary(other.salary) {}

// Method to display employee details


void display() {

cout << "Name: " << name << endl;


Q.No. TOTAL
E 25
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.1
cout << "Age: " << age << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
// Creating an employee object using the copy constructor
Employee emp1("John Doe", 30, 5000);
// Creating another employee object using the copy constructor
Employee emp2 = emp1;
cout << "Employee 1 Details:" << endl;
emp1.display();
cout << "\nEmployee 2 Details (Copied from Employee 1):" << endl;
emp2.display();
return 0;
}

Program Explanation :
- The code defines a class called Employee with private member variables for name,
age, and salary.
- The class Employee includes a public member function called display() to output
the employee details.
- In the main() function, an Employee object named emp1 is created using a
parameterized constructor with specific values for name, age, and salary. Then,
another Employee object named ‘emp2’ is created by using the copy constructor to
copy the values from emp1 to ‘emp2’.

Output :
Employee 1 Details:
Name: raj rathod
Age: 30
Salary: 5000
Q.No. TOTAL
E 26
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.4
Employee 2 Details (Copied from Employee 1):
Name: raj rathod
Age: 30
Salary: 5000
Q.No. TOTAL
E 27
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.5
 a) Definition of user defined exception :
- user-defined exception refers to creating a custom exception class by the
programmer to handle specific error conditions that may arise during the execution
of a program.
- These exceptions are derived from the standard exception classes provided by C++.

scenarios where user-defined exceptions can be useful in C++:


- User-defined exceptions allow programmers to handle specific error conditions in
their code, such as insufficient funds in a banking application.
- Custom exceptions can be defined to handle domain-specific scenarios, like invalid
input parameters in a scientific simulation program.
- User-defined exceptions can be organized in a hierarchy, allowing for catching
specific exceptions at different levels of the program.
- This provides a more structured approach to error handling.

C++ program that demonstrate the user defined exception


#include <iostream>
Using namespace std;

class MyException {
public:
char* what() {
return "Something went wrong!";
}
};

int main() {
try {
throw MyException();
}
Q.No. TOTAL
E 28
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.5

catch (const MyException& e) {


cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}

Program explanation :
- The program defines a user-defined exception class “MyException”. In the
“main()” function, it throws an instance of “MyException” and catches it using a
“catch” block.
- The caught exception's error message is then printed to the console.
Output :
Caught exception:
Something went wrong!

 b) Definition of namespace :
- Namespaces are used to group the entities like class, variables, objects, function
under a name.
- The namespaces help to divide global scope into sub-scopes, where each sub-scope
has its own name.
Example:
#include <iostream>
using namespace std;
namespace ns1 {
int a = 5;
}
namespace ns2 {
char a[] = "Hello";
}
Q.No. TOTAL
E 29
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.5

int main() {
cout << ns1::a << endl;
cout << ns2::a << endl;
return 0;
}

Program Explanation:
- In above program there are two different namespaces containing the variable a. -
- The variable a in the first namespace ns1 is of type int but the variable a in the
second namespace ns2 is of array of characters.
- The both the entities are treated separately. There is no re-declaration error for
variable a.

Rules of Namespaces
1) The namespace must be defined using the keyword namespace.
2) The namespace definition must appear at the global scope, or it can be present
inside another namespace(i.e. nested)
3) The definition of namespace must not be terminated with semicolon.
4) It is not allowed to create an instance of: namespace.
5) There can be unnamed namespace as well.
6) The namespace definition is valid over multiple files. There is no need to redefine
it across multiple files.
7) The namespace declaration do not have access specifiers (public or private)

 C) Function template :
- To perform identical operation for each type of data compactly and conveniently,
the function templates are used.
- The syntax of function template is follows :
Template<class name_of_data_type>
Name_of_data_type function_name(name_of_data_type id1,… name_of_data_type id2)
Q.No. TOTAL
E 30
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.5

For example : Template<classT>


T min(T a, T b)
- Here template is a keyword used to represent the template, then inside the angular
bracket keyword class is followed by the data type name T.
- the compiler will replace T by the appropriate data types.

The complete program using class template is given below :


#include <iostream>
template <class T>
T minimum(T a, T b) {
if (a < b)
return a;
else
return b;
}
int main() {
std::cout << "min(10, 20) = " << minimum(10, 20) << std::endl;
std::cout << "min('p', 't') = " << minimum('p', 't') << std::endl;
std::cout << "min(10.3, 67.2) = " << minimum(10.3, 67.2) << std::endl;
return 0;
}

Code explanation :
- The program uses a function template called “minimum” to find the minimum
value between two elements of the same type.
- It compares different data types (“int”, “char”, “double”) and displays the
minimum values.
Output:
min(10, 20) = 10
min('p', 't') = p
Q.No. TOTAL
E 31
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.5
min(10.3, 67.2) = 10.3

Class template:
- Using class template we can write a class whose members use template parameters
as types.
- The syntax of ciass template declaration is :
Template<class type>class classname {
//body of class
};

- In above example , type can be of any data types , then template class member
function is defined.
The complete program using class template is given below
#include <iostream>
Using namespace std;
template <class T>
class Compare {
T a, b;
public:
Compare(T first, T second) {
a = first;
b = second;
}
T max() {
T val;
if (a > b)
val = a;
else
val = b;
return val;
Q.No. TOTAL
E 32
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.5
}
};
int main() {
Compare<int> obj1(100, 60);
Compare<char> obj2('p', 't');
cout << "Maximum of 100 and 60: " << obj1.max() << endl;
cout << "Maximum of 'p' and 't': " << obj2.max() << endl;
return 0;
}

Code explanation :
This code defines a class template “Compare” that compares two values of the
same type and finds the maximum among them.
It demonstrates the usage of class templates and how they can be instantiated
with different types (“int” and “char” in this case) to perform the comparison.

output:
Maximum of 100 and 60: 100
Maximum of 'p' and 't': t
Q.No. TOTAL
E 33
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.6
 a) Definition of stream :
- streams are used for input and output operations. They represent the flow of data
to or from a device, such as the console or a file.
- Streams provide a standardized way to handle reading and writing data, abstracting
the complexities of interacting with different devices.

types of streams available in C++:


1. Input Streams (“istream”):
- Used for reading data from a device.
- Examples: “cin” (standard input stream), file input streams (“ifstream”).
- Functions: “>>“ (extraction operator), “getline()”.

2. Output Streams (“ostream”):


- Used for writing data to a device.
- Examples: “cout” (standard output stream), file output streams (“ofstream”).
- Functions: “<<“ (insertion operator).

3. Input/Output Streams (“iostream”):


- Combined functionality of input and output streams.
- Can be used for both reading and writing data to a device.
- Examples: “cin”, “cout”.

Additional derived stream classes:-


- “ifstream”: Input stream for reading from files.
- “ofstream”: Output stream for writing to files.
- “stringstream”: Stream for reading from and writing to strings.

Streams provide a standardized and flexible way to handle input and output
operations in C++, abstracting the complexities of interacting with different devices.
Q.No. TOTAL
E 34
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.6
 b) Definition of namespace :
- Namespaces are used to group the entities like class, variables, objects, function
under a name.
- The namespaces help to divide global scope into sub-scopes, where each sub-scope
has its own name.

Example:
#include <iostream>
using namespace std;

namespace ns1 {
int a = 5;
}
namespace ns2 {
char a[] = "Hello";
}
int main() {
cout << ns1::a << endl;
cout << ns2::a << endl;
return 0;
}
Program Explanation:
- In above program there are two different namespaces containing the variable a.
- The variable a in the first namespace ns1 is of type int but the variable a in the
second namespace ns2 is of array of characters.
- The both the entities are treated separately. There is no re-declaration error for
variable a.
Q.No. TOTAL
E 35
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.6
Rules of Namespaces
1) The namespace must be defined using the keyword namespace.
2) The namespace definition must appear at the global scope.
3) The definition of namespace must not be terminated with semicolon.
4) It is not allowed to create an instance of: namespace.
5) There can be unnamed namespace as well.
6) The namespace definition is valid over multiple files. There is no need to redefine
it across multiple files.
7) The namespace declaration do not have access specifiers (public or private)

 C) comparison between late binding & early binding


Q.No. TOTAL
E 36
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.7
 a) error handling during file operations :
- When error occurs in file handling, flags are set in the state according to the
general category of the error.
- When error occurs while performing file I/O operations, the appropriate message is
displayed and then the file terminates.
- Flags and their error categories are summarized in the following table.

Following program illustrates how to use appropriate error messages on


corresponding read and write error-causing situations
#include <iostream>
#include <fstream>
#include <cstdlib>
Using namespace std;
Const int MAX = 10;
Int array1[MAX] = {10, 20, 30, 40, 50};
Int array2[MAX];
Int main(){
Ofstream os;
Os.open(“d:\\test.dat”, ios::trunc | ios::binary);
If (!os)
{
Q.No. TOTAL
E 36
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.7
Cerr << “Could not open output file\n”;
Exit(1);
}
Cout << “Writing the contents to the file…\n\n”;
Os.write(reinterpret_cast<char*>(&array1), sizeof(array1));
If (!os)
{
Cerr << “Could not write to file\n”;
Exit(1);
}
Os.close();
Ifstream is;
Is.open(“d:\\test.dat”, ios::binary);
If (!is) {
Cerr << “Could not open input file\n”;
Exit(1);
}
Cout << “Reading the contents from the file…\n”;
Is.read(reinterpret_cast<char*>(&array2), sizeof(array2));
If (!is)
{
Cerr << “Could not read from file\n”;
Exit(1);
}
Is.close();
Cout << “Data read from the file:\n”;
For (int j = 0; j < MAX; j++) {
Cout << array2[j] << “ “;
}
Q.No. TOTAL
E 38
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.7
Cout << endl;
Return 0;
}

Output
Writing the contents to the file...
Reading the contents from the file…
10 20 30 40 50 0 0 0 0 0

Program explanation:
- In above program we have created one array of integers namely arrayl. Then in
the test.dat file the contents of this array are written.
- Again the file is opened in read mode and contents of the file are read in another
array namely array2 and then those contents are displayed on the console.
- During, open, read and write modes of the file, appropriate error handling is done.
Using the cerr the error messages can be displayed.

 b) program using put ( ) to write characters to a file until user enteres a dollar
sign.
#include <iostream>
#include <fstream>
Using namespace std;
Int main()
{
ofstream outputFile(“output.txt”); // Open the file for writing
Char ch;
cout << “Enter characters to write to the file (enter $ to stop):\n”;
// Read characters from user input and write them to the file
Q.No. TOTAL
E 39
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.7
While (cin.get(ch) && ch != ‘$’) {
outputFile.put(ch);
}
outputFile.close(); // Close the file
cout << “Data written to file successfully.\n”;
return 0;
}

Program explanation:
- The program uses “ofstream” to write characters to a file.- It prompts the user
to enter characters until they input a dollar sign (“$”).
- Characters entered by the user are written to the file using “put()”.
- The program closes the file and displays a success message.Remember to compile
and run the program to test it.
After running the program, you can check the "output.txt" file to see the characters
that were entered before the dollar sign.

Output :
Enter characters to write to the file (enter $ to stop):
Hello, world!
This is a test.
$
Data written to file successfully.

 C) file operating modes :


- Operating modes in file systems refer to the different ways in which files can be
accessed and manipulated.
- These modes determine the level of access and permissions granted to users or
processes when interacting with files.
Q.No. TOTAL
E 40
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.7
commonly used file operating modes:

example :
- if a file “new” is open in out mode It will be done by the following two statement
ofstream o ;
o.open(“test”, ios::out);
- Another example to open a file “new” input mode the statement can be given
below
ifstream i ;
i.open(“test”, ios::in);
- For opening file in a input and output mode the statement can be given below
Ifstream i ;
i.open(“test”, ios::in | ios::out);
- To close a file the function close is to used this can be done as a shown in
below,
i.close();
Q.No. TOTAL
E 41
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.8
 a) definition of manipulator :
- manipulator is a special function or object that is used to modify the behavior or
formatting of input/output operations.
- Manipulators can be used with input streams (e.g., cin) or output streams (e.g.,
cout) to control various aspects such as formatting, precision, positioning, and more

some manipulators for file handling in C++ along with their definitions, syntax, and
usage:
1. “setw(int n)”:
- Definition: Sets the field width of the output stream to “n” characters.
- Syntax: “cout << setw(n)”
- Usage: It is used to control the width of the output field, ensuring that the
following output is padded or truncated accordingly.

2. “endl”:
- Definition: Inserts a new line character into the output stream and flushes the
stream.
- Syntax: “cout << endl”
- Usage: It is used to insert a line break and flush the output buffer, ensuring
that any buffered data is immediately written to the output file.

3. “seekg(int position)”:
- Definition: Sets the position of the get pointer in the input stream.
- Syntax: “file.seekg(position)”
- Usage: It is used to set the position of the get pointer within the input file,
allowing you to read from a specific location within the file.

4. “seekp(int position)”:
- Definition: Sets the position of the put pointer in the output stream.
- Syntax: “file.seekp(position)”
Q.No. TOTAL
E 42
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.8

- Usage: It is used to set the position of the put pointer within the output file,
allowing you to write to a specific location within the file.

5. “tellg()”:
- Definition: Returns the current position of the get pointer in the input stream.
- Syntax: “file.tellg()”
- Usage: It is used to retrieve the current position of the get pointer within the
input file.

6. “tellp()”:
- Definition: Returns the current position of the put pointer in the output stream.
- Syntax: “file.tellp()”
- Usage: It is used to retrieve the current position of the put pointer within the
output file.

7. “binary”:
- Definition: Sets the file mode to binary mode.
- Syntax: “file.open(filename, ios::binary)”
- Usage: It is used to open the file in binary mode, allowing you to read or write
binary data.

- These manipulators can be utilized to control formatting, positioning, and behavior


when working with files, enabling precise control over input/output operations..
Q.No. TOTAL
E 43
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.8
 b) File Pointer:
- A file pointer is a mechanism used in file handling to keep track of the current
position within a file.

- It represents the position from which the next read or write operation will occur.

- The file pointer moves automatically as data is read from or written to the file,
ensuring sequential access to file content.

- It acts as a reference point for the operating system to determine the location to
read from or write to within a file.

File Opening:
- File opening establishes a connection between a program and a file, enabling
access and manipulation of its content.
- In C++, the "fstream" library is commonly used for file opening operations.
- The file mode is specified using flags like "ios::in" for input (read) mode, "ios::out"
for output (write) mode, and "ios::app" for append mode.

The steps involved in file opening are as follows:

step 1 : Include the necessary header file: #include <fstream>


- Ensures availability of file handling functions and classes.

step 2 : Declare an object of type "fstream" to represent the file: fstream file;
- Creates a file object for file operations.

step 3 : Open the file using the "open()" function, providing the file name and
mode: file.open("filename.txt", ios::mode);
- Specifies the file to open and the desired file mode.
Q.No. TOTAL
E 44
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.8

step 4 : Check if the file opening was successful: if (file.is_open()) { /* File opened
successfully */ }
- Verifies if the file was opened successfully to handle any errors.

File Closing:
- File closing is the process of disconnecting the program from a file, freeing up
system resources, and ensuring that all data has been written to the file.
- It is considered good practice to close files after you have finished using them.
- In C++, file closing is typically performed by calling the “close()” function on
the file object.

Closing a file involves the following steps:


Step 1. Use the close() function on the file object: file.close();
- This function closes the file and releases associated resources.

Step 2. Check if the file closure was successful: if (file.is_open()) { /* File closure
failed */ }
- Verify that the file is successfully closed to handle any potential errors.

 C) stream classes hierarchy for file handling :

- the stream classes hierarchy for file handling is based on the concept of
inheritance and polymorphism.
- The stream classes hierarchy in C++ allows for modular and flexible file handling.
- Each class in the hierarchy builds upon the functionalities provided by its base
class, allowing for specialized operations for input, output, or both.
- Depending on the specific needs of your program, you can choose the appropriate
stream class for reading, writing, or bidirectional operations on files.
Q.No. TOTAL
E 45
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.8
- Stream classes hierarchy as shown in below figure:

The hierarchy consists of the following stream classes:


1. ios:
- The base class for all I/O stream classes.
- Provides basic I/O functionality, such as opening and closing files, error handling,
and formatting options.

2. istream:
- Derived from ios.
- Used for input operations from a stream.
- Provides functions like “operator>>“ to extract data from a stream.

3. ostream:
- Derived from ios.
- Used for output operations to a stream.
- Provides functions like “operator<<“ to insert data into a stream.
4. iostream:
Q.No. TOTAL
E 46
Savitribai Phule Pune University M SPPU HUB

प्र.क्र./Q. No.

Q.8
4. iostream:
- Derived from both istream and ostream.
- Combines the functionalities of both input and output streams.
- Allows bidirectional stream operations (input and output) on a stream.

5. ifstream:
- Derived from istream.
- Used for reading data from a file.
- Provides additional functions specific to file input operations, such as opening
files and checking end-of-file.

6. ofstream:
- Derived from ostream.
- Used for writing data to a file.
- Provides additional functions specific to file output operations, such as creating
files and controlling file truncation.

7. fstream:
- Derived from iostream.
- Provides the combined functionalities of both ifstream and ofstream.
- Allows both input and output operations on a file.

You might also like