2081

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.

  1. 110 marksBinary file reading and writingAnswer

    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::binary flag along with the file mode:

    ifstream fin("file.dat", ios::in | ios::binary);   // reading
    ofstream fout("file.dat", ios::out | ios::binary);  // writing
    

    Writing 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.TXT
    
    Enter an integer: 250
    250 has been written to LARGE.TXT
    

    Explanation of Key Steps

    StepDescription
    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 use ios::out if overwriting is acceptable.

  2. 210 marksStructures versus classesAnswer

    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++, struct and class are almost identical, with one key difference:

    FeatureStructure (struct)Class (class)
    Default access specifierPublicPrivate
    Default inheritancePublicPrivate
    General useSimple data groupingFull OOP with data hiding

    Example:

    struct S { int x; };   // x is public by default
    class C { int x; };    // x is private by default
    

    In C++, a struct can 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 friend inside 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

    TypeArgumentsPurpose
    Default ConstructorNoneInitializes object with default values
    Parameterized ConstructorOne or moreInitializes object with given values
    Copy ConstructorReference to same class objectCreates 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
  3. 310 marksInheritance definition and purposeAnswer

    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...

  4. 45 marksFeatures of object-oriented programmingAnswer

    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 ...

  5. 55 marksAbstract classes and concrete classesAnswer

    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 ...

  6. 65 marksException handling definition and purposeAnswer

    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...

  7. 75 marksReturning objects from functionsAnswer

    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...

  8. 85 marksOverloading unary operatorsAnswer

    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...

  9. 95 marksInline functionsAnswer

    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. --- -...

  10. 105 marksType conversionAnswer

    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...

  11. 115 marksStream manipulatorsAnswer

    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...

  12. 125 marksOperator overloading definition and purposAnswer

    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:

    1. Readability and Natural Syntax Allows objects to be used with operators in a natural, intuitive way. For example: c3 = c1 + c2 for complex number objects instead of c3 = c1.add(c2).

    2. Code Simplicity Reduces the need for verbose function calls, making code cleaner and easier to maintain.

    3. 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.

    4. Consistency Provides consistent interface for user-defined types similar to built-in types, so the same operator behaves logically across different data types.

    5. 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
           \ /
            D
    

    Example:

    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

    ProblemCauseSolution
    AmbiguitySame name in multiple base classesScope resolution (::)
    Diamond ProblemCommon base class inherited twiceVirtual 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.