BIT153 · TU past paper
Object Oriented Programming 2081 question paper
The complete TU 2081 exam paper for Object Oriented Programming (BIT153), all 12 questions with solved model answers written to the mark scheme.
Tap a question to open its answer.
- 110 marksBinary file reading and writingHideAnswer
Define stream.How do you read and write binary files?Write a program to read an integer from the user and if the integer is less than 100 then write it in file named "SMALL.TXT" otherwise write in file named "LARGE.TXT".[2+3+5]
Streams, Binary File I/O, and File Writing Program
1. Definition of Stream (2 marks)
A stream is an abstraction that represents a flow of data between a program and an input/output device (such as a keyboard, monitor, disk file, etc.).
- A stream acts as a logical interface between the program and the actual I/O device.
- In C++, streams are implemented through a hierarchy of classes defined in headers like
<iostream>and<fstream>. - There are two main types:
- Input Stream: Data flows into the program (e.g., reading from a file or keyboard).
- Output Stream: Data flows out of the program (e.g., writing to a file or screen).
Key stream classes:
ifstream(input file stream),ofstream(output file stream),fstream(both input and output).
2. Reading and Writing Binary Files (3 marks)
Binary files store data in the same format as it is stored in memory (raw bytes), unlike text files which store data as readable characters.
Opening a Binary File
Use the
ios::binaryflag along with the file mode:ifstream fin("file.dat", ios::in | ios::binary); // reading ofstream fout("file.dat", ios::out | ios::binary); // writingWriting to a Binary File
Use the
write()member function:fout.write((char*) &variable, sizeof(variable));- The first argument is a pointer to the data cast to
char*. - The second argument is the number of bytes to write.
Reading from a Binary File
Use the
read()member function:fin.read((char*) &variable, sizeof(variable));Example
#include <fstream> using namespace std; int main() { int num = 42; // Write binary ofstream fout("data.bin", ios::out | ios::binary); fout.write((char*) &num, sizeof(num)); fout.close(); // Read binary int readNum; ifstream fin("data.bin", ios::in | ios::binary); fin.read((char*) &readNum, sizeof(readNum)); fin.close(); return 0; }
3. Program: Write Integer to SMALL.TXT or LARGE.TXT (5 marks)
#include <iostream> #include <fstream> using namespace std; int main() { int num; // Read integer from user cout << "Enter an integer: "; cin >> num; if (num < 100) { // Write to SMALL.TXT ofstream fout("SMALL.TXT", ios::app); // ios::app to append if (!fout) { cout << "Error opening SMALL.TXT!" << endl; return 1; } fout << num << endl; fout.close(); cout << num << " has been written to SMALL.TXT" << endl; } else { // Write to LARGE.TXT ofstream fout("LARGE.TXT", ios::app); // ios::app to append if (!fout) { cout << "Error opening LARGE.TXT!" << endl; return 1; } fout << num << endl; fout.close(); cout << num << " has been written to LARGE.TXT" << endl; } return 0; }Sample Output
Enter an integer: 45 45 has been written to SMALL.TXTEnter an integer: 250 250 has been written to LARGE.TXTExplanation of Key Steps
Step Description cin >> numReads integer from the user if (num < 100)Checks the condition ofstream fout("SMALL.TXT", ios::app)Opens SMALL.TXT in append mode ofstream fout("LARGE.TXT", ios::app)Opens LARGE.TXT in append mode if (!fout)Checks if file opened successfully fout << numWrites the integer to the file fout.close()Closes the file after writing Note:
ios::app(append mode) is used so that previously written values are not overwritten each time the program runs. You may also useios::outif overwriting is acceptable. - 210 marksStructures versus classesHideAnswer
How does structure differ with class?What are the uses of friend function and friend class?Explain the types of constructors.[1+3+6]
Structure vs Class, Friend Functions/Classes, and Types of Constructors
1. How does Structure differ with Class?
In C++,
structandclassare almost identical, with one key difference:Feature Structure ( struct)Class ( class)Default access specifier Public Private Default inheritance Public Private General use Simple data grouping Full OOP with data hiding Example:
struct S { int x; }; // x is public by default class C { int x; }; // x is private by defaultIn C++, a
structcan also have member functions, constructors, and inheritance, just like a class.
2. Uses of Friend Function and Friend Class
Friend Function
A friend function is a non-member function that is granted access to the private and protected members of a class by declaring it with the keyword
friendinside the class.Uses:
- To allow an external function to access private data of a class
- Useful for operator overloading (e.g.,
<<,>>) - To allow two classes to share data without making members public
Syntax:
class Box { private: int length; public: Box(int l) { length = l; } friend void showLength(Box b); // friend declaration }; void showLength(Box b) { cout << "Length: " << b.length; // accesses private member }
Friend Class
A friend class is a class that is granted access to the private and protected members of another class.
Uses:
- When two closely related classes need to share private data
- Useful in implementing container and iterator relationships
Syntax:
class Engine { private: int horsepower; public: Engine(int hp) { horsepower = hp; } friend class Car; // Car is a friend of Engine }; class Car { public: void show(Engine e) { cout << "HP: " << e.horsepower; // accesses private member } };Note: Friendship is not inherited and not mutual (if A is a friend of B, B is not automatically a friend of A).
3. Types of Constructors
A constructor is a special member function that has the same name as the class, has no return type, and is automatically called when an object is created. It is used to initialize objects.
Type 1: Default Constructor
A constructor that takes no arguments (or all arguments have default values).
- Automatically provided by the compiler if no constructor is defined
- Called when an object is created without any arguments
class Student { public: int roll; string name; Student() { // Default constructor roll = 0; name = "Unknown"; } }; int main() { Student s; // Default constructor called }
Type 2: Parameterized Constructor
A constructor that accepts one or more arguments to initialize an object with specific values.
- Allows different objects to be initialized with different values
- Supports constructor overloading
class Student { public: int roll; string name; Student(int r, string n) { // Parameterized constructor roll = r; name = n; } }; int main() { Student s1(1, "Ram"); Student s2(2, "Sita"); }
Type 3: Copy Constructor
A constructor that creates a new object as a copy of an existing object. It takes a reference to an object of the same class as its parameter.
- Called when an object is initialized from another object
- Called when an object is passed by value to a function
- Called when an object is returned by value from a function
class Student { public: int roll; string name; Student(int r, string n) { roll = r; name = n; } Student(const Student &s) { // Copy constructor roll = s.roll; name = s.name; } }; int main() { Student s1(1, "Ram"); Student s2(s1); // Copy constructor called Student s3 = s1; // Copy constructor called }
Summary Table
Type Arguments Purpose Default Constructor None Initializes object with default values Parameterized Constructor One or more Initializes object with given values Copy Constructor Reference to same class object Creates a copy of an existing object
Key Points:
- A class can have multiple constructors (overloading)
- Constructors cannot be inherited but a derived class can call the base class constructor
- If any constructor is defined, the compiler does not provide a default constructor automatically
- 310 marksInheritance definition and purposeHideAnswer
List any two types of inheritance with example.Describe the order of execution of constructors and destructors in derived class.[5+5]
--- (a) Two Types of Inheritance with Examples When a derived class inherits from only one base class, it is called single inheritance. Syntax: Example: Diagram: --- When a derived class inherits from more than one base class, it is call...
- 45 marksFeatures of object-oriented programmingHideAnswer
Describe the features of object oriented programming. [5]
Note: No specific reference notes were found for this topic. The following answer is based on standard, well-established OOP concepts as taught in BSc CSIT curriculum. --- Object Oriented Programming (OOP) is a programming paradigm that ...
- 55 marksAbstract classes and concrete classesHideAnswer
Distinguish between concrete class and abstract class. Describe the roles of polymorphism. [5]
Feature Concrete class Abstract class --------- Definition Every member function it declares or inherits has a body It declares at least one pure virtual function, written virtual T f() = 0; Instantiation Objects can be created directly ...
- 65 marksException handling definition and purposeHideAnswer
Why do we need to handle exception? Illustrate with an example. [5]
An exception is an abnormal event detected while a program is running, such as a file that will not open, a request for memory that cannot be met, or an argument that makes an operation meaningless. In C++ the code that detects the troub...
- 75 marksReturning objects from functionsHideAnswer
How do you return object in function? Describe with an example. [5]
In C++, a function can return an object of a class just like it returns any other data type. The return type of the function is specified as the class name, and the return statement returns an object of that class. Syntax: --- - The retu...
- 85 marksOverloading unary operatorsHideAnswer
Write a program to create a class named STUDENT with data member age, then overload the unary operator (++) to increment the age of any object of above class. [5]
Unary operator overloading allows operators like ++, --, - etc. to work with user-defined class objects. The operator function is defined inside the class using the keyword operator followed by the operator symbol. --- --- --- Step Descr...
- 95 marksInline functionsHideAnswer
Explain advantages and disadvantages of inline function. [5]
An inline function is a function declared with the inline keyword that requests the compiler to replace the function call with the actual function body code at the point of invocation, rather than performing a normal function call. --- -...
- 105 marksType conversionHideAnswer
How do you convert basic data type to user defined data type? Explain. [5]
In C++, converting a basic (built-in) data type (such as int, float, double, char) to a user-defined data type (such as a class or struct) is achieved using a special constructor called a conversion constructor. --- A conversion construc...
- 115 marksStream manipulatorsHideAnswer
Illustrate the use of set w and set precision with example. [5]
setw and setprecision are output formatting manipulators defined in the header file <iomanip. They are used to control the appearance of output in C++. --- - Sets the minimum field width for the next output value. - The output is right-a...
- 125 marksOperator overloading definition and purposHideAnswer
What are the purposes of operator overloading? Address the problem in multiple inheritance. [5]
Operator Overloading and Problems in Multiple Inheritance
Purposes of Operator Overloading
Operator overloading allows existing C++ operators to be given additional meanings when applied to user-defined data types (classes). The main purposes are:
-
Readability and Natural Syntax Allows objects to be used with operators in a natural, intuitive way. For example:
c3 = c1 + c2for complex number objects instead ofc3 = c1.add(c2). -
Code Simplicity Reduces the need for verbose function calls, making code cleaner and easier to maintain.
-
Extensibility of Built-in Operators Extends the capability of built-in operators to work with user-defined types without changing the original meaning for primitive types.
-
Consistency Provides consistent interface for user-defined types similar to built-in types, so the same operator behaves logically across different data types.
-
Supports Data Abstraction Helps in implementing abstract data types (ADT) more effectively by hiding implementation details behind familiar operator syntax.
Problems in Multiple Inheritance
Multiple inheritance allows a derived class to inherit from more than one base class. However, it introduces several problems:
1. Ambiguity Problem (Name Conflict)
When two or more base classes have a member function or data member with the same name, the derived class becomes ambiguous about which one to use.
Example:
class A { public: void show() { cout << "Class A"; } }; class B { public: void show() { cout << "Class B"; } }; class C : public A, public B { // Ambiguous: which show() to call? }; int main() { C obj; obj.show(); // ERROR: ambiguous }Solution: Use scope resolution operator:
obj.A::show(); // calls A's show() obj.B::show(); // calls B's show()
2. Diamond Problem (Duplicate Inheritance / Deadly Diamond)
When a class inherits from two classes that both inherit from a common base class, the derived class ends up with two copies of the base class members, causing ambiguity and redundancy.
A / \ B C \ / DExample:
class A { public: int x; }; class B : public A { }; class C : public A { }; class D : public B, public C { // D has two copies of A::x // Ambiguous: B::x or C::x? };Solution: Use virtual base class to ensure only one copy of the base class is inherited.
class B : virtual public A { }; class C : virtual public A { }; class D : public B, public C { // Now only ONE copy of A exists };
Summary Table
Problem Cause Solution Ambiguity Same name in multiple base classes Scope resolution ( ::)Diamond Problem Common base class inherited twice Virtual base class ( virtual)
Note: These are standard C++ OOP concepts. No specific curriculum notes were available, so this answer is based on standard CS knowledge consistent with TU BSc CSIT syllabus.
-