May - Jun - OOPs Solved Question Papers-2019 Pattern
May - Jun - OOPs Solved Question Papers-2019 Pattern
Telegram Channel
https://t.me/SPPU_TE_BE_COMP
(for all engineering Resources)
WhatsApp Channel
(for all tech updates)
https://whatsapp.com/channel/
0029ValjFriICVfpcV9HFc3b
Insta Page
(for all engg & tech updates)
https://www.instagram.com/
sppu_engineering_update
[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.
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 ;
}
प्र.क्र./Q. No.
Q. 1
b) definition of scope resolution:
- Scope resolution operator are used to defining the scope of variable or Function.
When we want to use a global variable but also has local variable With same name.
in this case scope resolution operator are used to access the Variable value.
-It is donated by :: sign .
Program Explanation: The scope of the variable is always global. In this example,
we have a global variable “x” with a value of 5. Inside the “MyClass”, we have a
class member variable “x” with a value of 10. The member function “printX()”
displays both the class variable “x” and the global variable “x” using the scope
resolution operator “::”.
When we create an object “obj” of “MyClass” and call “obj.printX()”, it will
display the following output.
Q.No. TOTAL
E 3
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 1
Output :
Class variable: 10
Global variable: 5
प्र.क्र./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 ;
}
प्र.क्र./Q. No.
Q. 2
b) In C++, the following operators cannot be overloaded:
To overload the “+” operator to add two complex numbers, we can follow
these steps:
step 1 : Create a class named “Complex” to represent complex numbers with real
and imaginary parts.
step 2 : Declare the “+” operator either as a member or friend function of the
“Complex” class.
step 3 : If declared as a member function, define it inside the class; if declared
as a friend function, declare it inside and define it outside the class.
step 4 : Inside the “+” operator function, create a new “Complex” object to store
the sum.
step 5 : Add the real parts and imaginary parts of the two complex numbers and
assign the results to the corresponding members of the new object.
step 6 : Return the new “Complex” object.
step 7 : Utilize the overloaded “+” operator to add two complex numbers in your
program.
implementation :
#include <iostream>
class Complex {
public:
double real;
double imaginary;
Complex operator+(const Complex& other) {
Q.No. TOTAL
E 6
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 2
Complex result;
result.real = real + other.real;
result.imaginary = imaginary + other.imaginary;
return result;
}
};
int main() {
Complex c1, c2, sum;
c1.real = 2.0;
c1.imaginary = 3.0;
c2.real = 4.0;
c2.imaginary = 1.5;
sum = c1 + c2;
cout << "Sum: " << sum.real << " + " << sum.imaginary << "i" << endl;
return 0;
}
Code explanation :
- The code defines a “Complex” class to represent complex numbers. It overloads
the “+” operator to add two “Complex” objects together.
- In the “main” function, two “Complex” objects are created, their values are set,
and the “+” operator is used to add them. The sum is displayed as the result.
Output :
Sum: 6 + 4.5i
Q.No. TOTAL
E 7
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 2
c) 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 (--)
MyNumber operator--() {
number--;
return *this;
}
// Overloading logical not operator (!)
bool operator!() {
return (number == 0);
}
void display() {
cout << "Number: " << number << endl;
}
};
Q.No. TOTAL
E 8
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 2
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
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
Q.No. TOTAL
E 8
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
a) virtual base class :
definition : Virtual Base Class in C++ The virtual base class is a concept used in
multiple inheritances to prevent ambiguity between multiple instances.
- For example: suppose we created a class “A” and two classes “B” and “C”, are
being derived from class “A”. But once we create a class “D” which is being
derived from class “B” and “C” as shown in below figure.
- Class “A” is a parent class of two classes “B” and “C” And both “B” and “C”
classes are the parent of class “D”
- In the above figure class “A” will be inherited twice in class “D” because class
“B” and “C” are the parent classes of class “D” and they both are being derived
from class “A”.
- So when the class “D” will try to access the data member or member function
of class “A” it will cause ambiguity for the compiler and the compiler will throw
an error.
- To solve this ambiguity we will make class “A” as a virtual base class. To make
a virtual base class “virtual” keyword is used.
प्र.क्र./Q. No.
Q. 3
class A {
public:
void say(){
cout << "Hello world"<<endl;
}
};
class B :
public virtual A {
};
class C :
public virtual A {
};
class D : public B, public C {
};
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;
}
};
Q.No. TOTAL
E 10
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
class DerivedClass : public BaseClass{
public:
int var_derived=2;
void display(){
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.
प्र.क्र./Q. No.
Q. 3
- 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.
b) 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.
example :
Q.No. TOTAL
E 12
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
- 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.
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.
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.
Q.No. TOTAL
E 13
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
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
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
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 14
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 3
c) different ways in which inheritance promotes software reuse, saves time during
program development and helps prevent errors.
1. Software Reuse :
Inheritance enables code reuse by allowing new classes to inherit attributes
and behaviors from existing classes.Developers can build upon well-tested and reliable
base classes, eliminating the need to rewrite common functionality.This promotes
modularity, as code can be organized into reusable and extendable units, leading to
increased productivity and more efficient development.
2. Time Savings :
Inheritance saves time during program development by leveraging existing
code. Instead of starting from scratch, developers can focus on extending and
customizing the functionality of base classes. This reduces development effort and
speeds up the overall process, allowing developers to deliver software faster.
3. Error Prevention:
Inheritance helps prevent errors by promoting code reuse and reducing
redundancy. When common code is centralized in base classes, any changes or bug
fixes made to the base class automatically propagate to the derived classes. This
ensures consistency and avoids inconsistencies that can lead to errors. Additionally,
by avoiding code duplication, the chances of introducing bugs or inconsistencies are
minimized.
Q.No. TOTAL
E 15
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
a) Definition of ambiguity :
- Ambiguity in inheritance can be defined as when one class is derived for two or
more base classes then there are chances that the base classes have functions with
the same name.
- So it will confuse derived class to choose from similar name functions.
- To overcome this ambiguity scope resolution operator is used “::”.
- An example program is shown below to demonstrate the concept of ambiguity
resolution in inheritance.
#include<iostream>
using namespace std ;
class Base1{
public:
void greet(){
cout<<"How are you?"<<endl;
}
};
class Base2{
public:
void greet()
{
cout << "how are you?" << endl;
}
};
class Derived : public Base1, public Base2{
int a;
public:
void greet(){
Base2 :: greet();
}
};
Q.No. TOTAL
E 16
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
};
int main(){
Base1 base1obj;
Base2 base2obj;
base1obj.greet();
base2obj.greet();
Derived d;
d.greet();
return 0;
}
code explanation :
- in the above code we defines three classes: “Base1”, “Base2”, and “Derived”.
“Derived” inherits from both “Base1” and “Base2”.
- In the main function Object “base1obj” and “base3obj” is created of the “Base1”
and “Base2” data type.
- The function “greet” is called by the object “base1obj” and “base2obj”.
- after that Object “d” is created of the “Derived” data type. The function “greet”
is called by the object “d”
- the main think is that to resolve the ambiguity, the greet() function in Derived
explicitly calls Base2::greet(), specifying that the greet() function from Base2
should be used.
Output :
The output of the provided code will be:
"How are you?"
"how are you?"
"how are you?"
Q.No. TOTAL
E 17
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
b) 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.
example :
प्र.क्र./Q. No.
Q. 4
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.
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.
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.
Q.No. TOTAL
E 19
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
- In other word One class serves as a parent class for more than one class
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
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 20
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
c) role of access specifiers in inheritance
Access specifiers in inheritance determine the visibility of inherited members
in the derived class.
- Public: When inherited as public, public members of the base class remain public
in the derived class, protected members become protected, and private members
remain inaccessible directly.
- Protected: When inherited as protected, both public and protected members of
the base class become protected in the derived class, and private members remain
inaccessible directly.
- Private: When inherited as private, both public and protected members of the
base class become private in the derived class, and private members remain
inaccessible directly.
Visibility Example:
#include <iostream>
class Base {
public:
int publicData;
protected:
int protectedData;
private:
int privateData;
};
class DerivedPublic : public Base {
public:
void accessBaseData() {
publicData = 10; // Public member is accessible
protectedData = 20; // Protected member is accessible
// privateData = 30; // Error: Private member is not accessible
}
};
Q.No. TOTAL
E 21
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 4
};
class DerivedProtected : protected Base {
public:
void accessBaseData() {
publicData = 10; // Protected member is accessible
protectedData = 20; // Protected member is accessible
// privateData = 30; // Error: Private member is not accessible
}
};
प्र.क्र./Q. No.
Q. 4
code explanation :
- In the example, the “DerivedPublic” class publicly inherits from “Base”, making
both public and protected members accessible within the derived class.
- “DerivedProtected” class inherits protectedly from “Base”, making the inherited
members accessible only within the derived class and its derived classes.
- “DerivedPrivate” class privately inherits from “Base”, making the inherited
members accessible only within the derived class.
Q.No. TOTAL
E 23
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
a) 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)
For example :
Template<classT>
T min(T a, T b)
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.
प्र.क्र./Q. No.
Q. 5
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
min(10.3, 67.2) = 10.3
b) Exception handling:
- Exception handling is a mechanism in C++ to handle runtime errors or exceptional
situations in a program.
- It involves three keywords: try, catch, and throw.
- The try block contains statements that may result in exceptional conditions.
- When an exceptional condition occurs, it is thrown using the throw statement.
- The catch block is responsible for handling the thrown exception and taking
appropriate actions.
- The purpose of exception handling is to detect and report exceptional situations
in a program
- Exception handling helps improve code readability and maintainability by separating
error handling logic from regular code.
C++ program that demonstrates the handling of the divide-by-zero error:
#include <iostream>
using namespace std;
void divide(double a, double b) {
try {
if (b == 0)
throw b; // divide-by-zero
Q.No. TOTAL
E 25
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
cout << "Result: " << a / b << endl; // for non-zero value
}
catch (double) {
cout << "Can't divide by zero.\n";
}
}
int main() {
double i, j;
cout << "Enter numerator: ";
cin >> i;
cout << "Enter denominator: ";
cin >> j;
divide(i, j);
return 0;
}
Code explanation :
- The code takes input for the numerator and denominator, performs division, and
handles the case of dividing by zero.
- If the denominator is zero, it throws an exception and displays an error message.
Otherwise, it calculates and displays the result of the division.
Output :
Enter numerator: 20
Enter denominator: 0
Can't divide by zero.
c) Function template :
- To perform identical operation for each type of data compactly and conveniently,
the function templates are used.
Q.No. TOTAL
E 26
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 5
- 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)
- For example :
Template<classT>
T min(T a, T b)
- 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.
Code explanation :
- The program uses a function template called “minimum” to find the minimum
value between two elements of the same type.
Q.No. TOTAL
E 27
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
- It compares different data types (“int”, “char”, “double”) and displays the
minimum values.
Output:
min(10, 20) = 10
min('p', 't') = p
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 class 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.
प्र.क्र./Q. No.
T max() {
T val;
if (a > b)
val = a;
else
val = b;
return val;
}
};
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 29
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 6
a) class template using multiple parameters
- class templates allow us to define a generic class that can work with different
data types. Class templates can also have multiple template parameters, enabling
us to define a class that operates on multiple types simultaneously.
- The syntax for a class template with multiple parameters is as follows:
template <typename T1, typename T2, ...>
class ClassName {
// Class definition
};
- Here, “T1”, “T2”, etc., are the template parameters representing different types
that can be provided when creating an instance of the class.
प्र.क्र./Q. No.
Q. 6
};
int main() {
// Create an instance of Pair with int and double types
Pair<int, double> myPair(10, 3.14);
myPair.display();
// Create an instance of Pair with char and string types
Pair<char, string> anotherPair('A', "Hello");
anotherPair.display();
return 0;
}
Program explanation :
- In this program, we define a class template “Pair” with two template parameters,
“T1” and “T2”.
- The “Pair” class has two private members, “first” and “second”, of the respective
types.
- We create two instances of the “Pair” class, “myPair” and “anotherPair”, with
different types provided for “T1” and “T2”.
- We then call the “display” function on each instance to demonstrate the flexibility
of the class template with multiple parameters.
output
First: 10
Second: 3.14
First: A
Second: Hello
Q.No. TOTAL
E 31
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.
Output :
5
Hello
Q.No. TOTAL
E 32
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, 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) 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.
प्र.क्र./Q. No.
Q. 6
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”.
- 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
4
प्र.क्र./Q. No.
Q. 7
a) definition of file mode :
- file mode refers to the mode in which a file is opened for performing various
operations like reading, writing, or both. C++ supports various file modes, each
indicating a specific purpose for file access.
four commonly used file modes in C++ along with their syntax:
1. "ios::in":
- This mode is used for reading input from a file in C++.
- The file is opened for input operations only.
- Syntax: `ifstream file("filename", ios::in);`
- Allows us to read data from the file.
- We cannot modify or write to the file.
- Typically used with `ifstream` objects.
- Provides operations like `>>` and `getline()` to read data from the file.
2. "ios::out":
- This mode is used for writing output to a file in C++.
- The file is opened for output operations only.
- Syntax: `ofstream file("filename", ios::out);`:
- Allows us to write data to the file.
- We cannot read from the file.
- If the file already exists, its contents will be overwritten.
- Typically used with `ofstream` objects.
- Provides operations like `<<` to write data to the file.
3. "ios::app":
- This mode is used for appending data to an existing file in C++.
- The new data is added at the end of the file.
- Syntax: `ofstream file("filename", ios::app);`
- Allows us to append data to the file.
- The file is not overwritten; new data is added at the end.
Q.No. TOTAL
E 35
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7
- Typically used with `ofstream` objects.
- Useful for adding new entries to a log file or extending an existing file.
4. "ios::binary":
- This mode is used for performing binary input/output operations on a file.
- It is commonly used when dealing with non-text files or when preserving the
exact binary representation of data.
- Syntax: `fstream file("filename", ios::binary | ios::in | ios::out);`
- Treats the file as a sequence of raw bytes instead of text.
- Allows us to read and write binary data to the file.
- Can be used with both `ifstream` and `ofstream` objects.
- Useful for handling files like images, audio, or binary data files.
प्र.क्र./Q. No.
Q. 7
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)
{
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);
Q.No. TOTAL
E 37
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7
}
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] << “ “;
}
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.
Q.No. TOTAL
E 38
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 7
c) difference between opening a file with construction function& open ( )
function.
Q.No. TOTAL
E 39
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
a) C++ program that uses the “open()”, “eof()”, and “getline()” functions in
C++ to open and read file contents:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file;
std::string filename, line;
std::cout << "Enter the name of the file: ";
std::cin >> filename;
file.open(filename); // Open the file
Explanation program :
In this program, the user is prompted to enter the name of the file they want to
Q.No. TOTAL
E 40
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
read. The program attempts to open the file using “file.open(filename)”. If the file
is opened successfully, it proceeds to read and print the contents line by line using
a “while” loop and the “getline()” function. The loop continues until the end of
the file (EOF) is reached. Finally, the program closes the file using “file.close()”.
Output :
Enter the name of the file: example.txt
Hello
This is a sample file.
It contains multiple lines.
End of file.
file functions commonly used for text file and binary file operations :
Text File Operations:
1. “fstream”:
- Definition: The “fstream” class is used for handling text files, providing both
input and output functionalities.
- Syntax: “fstream file;”
2. “open()”:
- Definition: The “open()” function is used to open a text file with a specified
filename and mode.
- Syntax: “file.open("filename", mode);”
Q.No. TOTAL
E 41
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
3. “getline()”:
- Definition: The “getline()” function is used to read a line from a text file into
a string variable.
- Syntax: “getline(file, line);”
4. “eof()”:
- Definition: The “eof()” function checks whether the end of the file has been
reached.
- Syntax: “file.eof();”
2. “open()”:
- Definition: The “open()” function is used to open a binary file with a specified
filename and mode.
- Syntax: “file.open("filename", mode | ios::binary);”
3. “read()”:
- Definition: The “read()” function is used to read a block of data from a binary
file.
- Syntax: “file.read(reinterpret_cast<char*>(&buffer), sizeof(buffer));”
4. “write()”:
- Definition: The “write()” function is used to write a block of data to a binary
file.
- Syntax: “file.write(reinterpret_cast<const char*>(&data), sizeof(data));”
Q.No. TOTAL
E 42
Savitribai Phule Pune University M SPPU HUB
प्र.क्र./Q. No.
Q. 8
c) file opening mode :
- File opening modes determine how a file is opened and what operations can be
performed on it.
- There are several commonly used file opening modes available as fallow:
1. “ios::in” (Input mode):
- Used for reading from a file.
- The file must exist for successful opening; otherwise, the open operation will
fail.
- Example: “ifstream file("filename.txt", ios::in);”
प्र.क्र./Q. No.
Q. 8
- Example: “ifstream file("filename.bin", ios::in | ios::binary);”
These opening modes can be combined using the bitwise OR (“|”) operator
to perform multiple operations.
For example : “ios::in | ios::binary” represents opening a file in binary input mode.