2078

BIT153 · TU past paper

Object Oriented Programming 2078 question paper

The complete TU 2078 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 marksSingle-level inheritanceAnswer

    Create a class Employee with private data members Eid, Ename, and Salary. Include public member functions read and display value of data members. Derive a class names typist from above class. The class should contain a private data members. Finally create two objects of typist class and read and display their values.[10]

    Class Employee with Derived Class Typist in C++

    Concept Overview

    This problem demonstrates Inheritance in Object-Oriented Programming (OOP):

    • Base Class: Employee (with private members: Eid, Ename, Salary)
    • Derived Class: Typist (inherits from Employee, adds its own private member)
    • Two objects of Typist are created, and values are read and displayed.

    Complete C++ Program

    #include <iostream>
    #include <string>
    using namespace std;
    
    // Base Class: Employee
    class Employee {
    private:
        int Eid;
        string Ename;
        float Salary;
    
    public:
        // Member function to read data
        void read() {
            cout << "Enter Employee ID: ";
            cin >> Eid;
            cout << "Enter Employee Name: ";
            cin >> Ename;
            cout << "Enter Salary: ";
            cin >> Salary;
        }
    
        // Member function to display data
        void display() {
            cout << "Employee ID   : " << Eid << endl;
            cout << "Employee Name : " << Ename << endl;
            cout << "Salary        : " << Salary << endl;
        }
    };
    
    // Derived Class: Typist (inherits from Employee)
    class Typist : public Employee {
    private:
        int typingSpeed;   // words per minute (private data member of Typist)
    
    public:
        // Member function to read data (calls base class read)
        void read() {
            Employee::read();   // call base class read()
            cout << "Enter Typing Speed (words/min): ";
            cin >> typingSpeed;
        }
    
        // Member function to display data (calls base class display)
        void display() {
            Employee::display();   // call base class display()
            cout << "Typing Speed  : " << typingSpeed << " words/min" << endl;
        }
    };
    
    // Main Function
    int main() {
        Typist t1, t2;   // Two objects of Typist class
    
        // Reading values for first object
        cout << "\n--- Enter details for Typist 1 ---" << endl;
        t1.read();
    
        // Reading values for second object
        cout << "\n--- Enter details for Typist 2 ---" << endl;
        t2.read();
    
        // Displaying values for first object
        cout << "\n--- Details of Typist 1 ---" << endl;
        t1.display();
    
        // Displaying values for second object
        cout << "\n--- Details of Typist 2 ---" << endl;
        t2.display();
    
        return 0;
    }
    

    Sample Output

    --- Enter details for Typist 1 ---
    Enter Employee ID: 101
    Enter Employee Name: Ram
    Enter Salary: 25000
    Enter Typing Speed (words/min): 60
    
    --- Enter details for Typist 2 ---
    Enter Employee ID: 102
    Enter Employee Name: Sita
    Enter Salary: 22000
    Enter Typing Speed (words/min): 75
    
    --- Details of Typist 1 ---
    Employee ID   : 101
    Employee Name : Ram
    Salary        : 25000
    Typing Speed  : 60 words/min
    
    --- Details of Typist 2 ---
    Employee ID   : 102
    Employee Name : Sita
    Salary        : 22000
    Typing Speed  : 75 words/min
    

    Key Points to Remember

    FeatureDescription
    private membersEid, Ename, Salary in Employee; typingSpeed in Typist
    public inheritanceclass Typist : public Employee
    Employee::read()Scope resolution used to call base class function from derived class
    Two objectst1 and t2 are objects of Typist class
    EncapsulationPrivate data accessed only through public member functions

    Note: Since Eid, Ename, and Salary are private in Employee, they cannot be accessed directly in Typist. They are accessed through the public member functions read() and display() of the base class using Employee::read() and Employee::display().

  2. 210 marksOOP definition and conceptsAnswer

    What is object-oriented programming? How does it differ from procedure-oriented programming? Explain features of object oriented programming.[10]

    Object-Oriented Programming: Concepts, Comparison, and Features


    1. What is Object-Oriented Programming (OOP)?

    Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. An object is a self-contained unit that bundles together data (attributes) and behavior (methods/functions) that operate on that data.

    In OOP, real-world entities are modeled as objects. For example, a "Car" object has attributes like color, speed, and model, and behaviors like start(), stop(), and accelerate().

    Key idea:

    "OOP treats data as a critical element and does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it."


    2. Procedure-Oriented Programming (POP) vs Object-Oriented Programming (OOP)

    Procedure-Oriented Programming (POP)

    • Programs are divided into functions/procedures.
    • Focus is on what to do (the logic/algorithm).
    • Data is shared globally and can be accessed by any function.
    • Examples: C, Pascal, FORTRAN.

    Comparison Table

    FeatureProcedure-Oriented (POP)Object-Oriented (OOP)
    Basic UnitFunction / ProcedureObject
    FocusAlgorithm / LogicData
    Data AccessData is global, freely accessibleData is hidden (encapsulated)
    ApproachTop-downBottom-up
    Data SecurityLess secure (no data hiding)More secure (data hiding)
    Code ReusabilityLimited (functions can be reused)High (via inheritance)
    Real-world modelingDifficultNatural and easy
    MaintenanceHarder for large programsEasier due to modularity
    ExamplesC, Pascal, FORTRANC++, Java, Python

    Diagram: Data Flow Comparison

    POP:                          OOP:
      Function1                    [Object 1]
      Function2   <-- Global -->   [Object 2]   <-- Message Passing -->
      Function3       Data         [Object 3]
    

    In POP, data flows freely between functions. In OOP, objects communicate through message passing, keeping data protected.


    3. Features of Object-Oriented Programming

    3.1 Class

    • A class is a blueprint or template for creating objects.
    • It defines the attributes (data members) and behaviors (member functions) that objects of that class will have.
    • Example: class Student { string name; int roll; void display(); };

    3.2 Object

    • An object is an instance of a class.
    • It is the actual entity created from the class blueprint that occupies memory.
    • Example: Student s1; -- here s1 is an object of class Student.

    3.3 Encapsulation

    • Encapsulation is the mechanism of wrapping data and functions together into a single unit (class).
    • It restricts direct access to some components, protecting the internal state of an object.
    • Achieved using access specifiers: private, protected, public.
    • Benefit: Prevents accidental modification of data (data hiding).
    +-----------------------------+
    |         Class: BankAccount  |
    |-----------------------------|
    | - balance (private)         |  <-- Data hidden
    |-----------------------------|
    | + deposit()  (public)       |  <-- Accessible methods
    | + withdraw() (public)       |
    +-----------------------------+
    

    3.4 Abstraction

    • Abstraction means showing only the essential features of an object and hiding the unnecessary implementation details.
    • It reduces complexity and allows the programmer to focus on what an object does rather than how it does it.
    • Example: When you call car.start(), you don't need to know the internal combustion mechanism.
    • Achieved through abstract classes and interfaces.

    3.5 Inheritance

    • Inheritance is the mechanism by which one class (child/derived class) acquires the properties and behaviors of another class (parent/base class).
    • Promotes code reusability and establishes an "is-a" relationship.

    Types of Inheritance:

    TypeDescription
    SingleOne child inherits from one parent
    MultipleOne child inherits from multiple parents
    MultilevelChain of inheritance (A -> B -> C)
    HierarchicalMultiple children from one parent
    HybridCombination of above types
            Animal (Base Class)
               /        \
             Dog         Cat   (Derived Classes)
    

    3.6 Polymorphism

    • Polymorphism means "many forms". It allows the same function or operator to behave differently based on the context.
    • It enables one interface to be used for a general class of actions.

    Two types:

    TypeDescriptionExample
    Compile-time (Static)Resolved at compile timeFunction overloading, Operator overloading
    Run-time (Dynamic)Resolved at run timeFunction overriding (virtual functions)

    Example:

    // Function Overloading (Compile-time)
    int add(int a, int b)       { return a + b; }
    float add(float a, float b) { return a + b; }
    

    3.7 Message Passing

    • Objects communicate with each other by sending and receiving messages (calling methods).
    • A message specifies the name of the object, the method to invoke, and any parameters needed.
    • Example: s1.display(); -- object s1 receives the message to execute display().

    3.8 Dynamic Binding

    • Dynamic Binding (also called late binding) means the code to be executed in response to a function call is determined at runtime, not at compile time
  3. 310 marksConstructor definition and purposeAnswer

    Create a class called time that has separate int member data for hours, minutes, and seconds. One constructor should initialize this data to 0, and another should initialize it to fixed values. Another member function should display it, in 11:59:59 format. The final member function should add two objects of type time passed as arguments. A main() program should create two initialized time objects (should they be const) and one that isn't initialized. Then it should add the two initialized values together, leaving the result in the third time variable. Finally, it should display the value of this third variable Make appropriate member functions const.[10]

    --- --- Field t1 t2 Raw Sum Carry Final ---------------------------------------- Seconds 30 45 75 1 min 15 Minutes 45 20 65 + 1 = 66 1 hr 06 Hours 5 6 11 + 1 = 12 -- 12 Result: 12:06:15 -- correct. --- Concept Detail ------ Default Const...

  4. 45 marksMemory management operatorsAnswer

    Explain Memory Management Operators of C++ with example. [5]

    C++ provides two special memory management operators for dynamic memory allocation and deallocation at runtime: 1. new operator 2. delete operator These operators allow programs to request memory from the heap (free store) during program...

  5. 55 marksCall by value and call by referenceAnswer

    Explain Call by Value and Call by Reference with appropriate example. [5]

    In Call by Value, a copy of the actual argument is passed to the formal parameter of the function. Any changes made to the formal parameter inside the function do not affect the original (actual) argument. - The actual and formal paramet...

  6. 65 marksTypes of constructorsAnswer

    Describe types of constructors with an example. [5]

    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. --- A constructor that takes no parameters. It is called automatically when an obj...

  7. 75 marksObjects as function argumentsAnswer

    Explain use of objects as function arguments with example [5]

    In C++, objects of a class can be passed as arguments to functions, just like variables of built-in data types. This allows functions to work with the data and behavior encapsulated within objects. When an object is passed to a function,...

  8. 85 marksType conversionAnswer

    Lost out various type conversion techniques? Explain basic to user-defined type conversion with example. [5]

    Type conversion refers to the process of converting a value from one data type to another. C++ supports several type conversion techniques. --- - Done automatically by the compiler. - Converts lower data type to higher data type (no data...

  9. 95 marksEarly binding versus late bindingAnswer

    How-late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example. [5]

    Late Binding vs Early Binding and Dynamic Polymorphism

    Early Binding (Static Binding)

    Early binding means the compiler resolves the function call at compile time. The decision of which function to call is made before the program runs.

    • Also called compile-time binding or static polymorphism
    • Examples: function overloading, operator overloading
    • Faster execution since binding is done at compile time

    Late Binding (Dynamic Binding)

    Late binding means the function call is resolved at run time, not at compile time. The decision of which function to execute depends on the actual object type during execution.

    • Also called run-time binding or dynamic polymorphism
    • Achieved using virtual functions and pointers/references to base class
    • Slightly slower due to run-time lookup (via vtable), but provides flexibility

    Key Differences

    FeatureEarly BindingLate Binding
    Resolution timeCompile timeRun time
    MechanismOverloadingVirtual functions
    FlexibilityLess flexibleMore flexible
    SpeedFasterSlightly slower
    Polymorphism typeStaticDynamic

    Dynamic Polymorphism

    Dynamic polymorphism is achieved in C++ by:

    1. Declaring a function as virtual in the base class
    2. Overriding that function in derived classes
    3. Using a base class pointer or reference to call the function

    Example

    #include <iostream>
    using namespace std;
    
    class Shape {
    public:
        virtual void draw() {          // virtual function -> late binding
            cout << "Drawing Shape" << endl;
        }
    };
    
    class Circle : public Shape {
    public:
        void draw() override {         // overriding in derived class
            cout << "Drawing Circle" << endl;
        }
    };
    
    class Rectangle : public Shape {
    public:
        void draw() override {         // overriding in derived class
            cout << "Drawing Rectangle" << endl;
        }
    };
    
    int main() {
        Shape *ptr;                    // base class pointer
    
        Circle c;
        Rectangle r;
    
        ptr = &c;
        ptr->draw();    // Output: Drawing Circle   (resolved at run time)
    
        ptr = &r;
        ptr->draw();    // Output: Drawing Rectangle (resolved at run time)
    
        return 0;
    }
    

    Output

    Drawing Circle
    Drawing Rectangle
    

    Explanation

    • ptr is a pointer of type Shape*
    • At compile time, the compiler cannot determine which draw() to call
    • At run time, the actual object (Circle or Rectangle) determines which version of draw() executes
    • This is late binding in action, enabling dynamic polymorphism

    Note: Without the virtual keyword, early binding would occur and Shape::draw() would always be called regardless of the actual object type.

  10. 105 marksPure virtual functionsAnswer

    Explain pure virtual functions with example. [5]

    A pure virtual function is a virtual function that has no implementation in the base class and is declared by assigning = 0 in its declaration. It forces every derived class to provide its own implementation of that function. Syntax: ---...

  11. 115 marksException handling definition and purposeAnswer

    What is exception handling? Explain how to handle an exception with appropriate example. [5]

    Exception Handling in C++ and How an Exception Is Handled

    What exception handling is

    Exception handling is the mechanism by which a program signals a fault at the place where it is discovered and deals with it at the place that has enough context to decide what to do. An exception is an unexpected condition that arises while the program runs, such as a file that will not open, memory that cannot be allocated, or an argument that makes an operation meaningless, and which would otherwise leave the program with no sensible way to continue.

    In C++ the mechanism has three parts. Code that detects the fault executes throw, which creates an exception object. The runtime then searches outward through the enclosing try blocks for a catch handler whose type matches that object. On the way out it destroys every local object created since the try block was entered, in reverse order of construction. That destruction is called stack unwinding, and it is what makes the whole thing safe to use.

    The constructs involved

    ConstructPurpose
    tryEncloses the code whose exceptions are to be handled
    catchHandles one type of exception; several may follow one try
    throwRaises an exception; written bare inside a handler it rethrows the current one
    catch (...)Catches an exception of any type whatsoever
    DestructorsRun automatically during unwinding and perform the cleanup

    Notice what is missing. C++ has no finally block, because it does not need one: cleanup goes into the destructor of the object that owns the resource, and that destructor is guaranteed to run whether the block is left normally or through an exception. The idiom is called RAII, resource acquisition is initialisation.

    Most thrown types derive from std::exception, whose member what() returns a description. <stdexcept> supplies the usual ones, std::runtime_error, std::out_of_range, std::invalid_argument among them, so a single handler for const std::exception& can cover the whole family.

    The flow when an exception is thrown

    The statements in the try block run in order. If none of them throws, every handler is skipped and execution continues after the last one. If one of them throws, the rest of the try block is abandoned, the local objects built so far are destroyed, and the handlers are examined top to bottom until one whose type matches is found. That handler runs, and execution then resumes after the last handler, not back inside the try block. If no handler in the whole program matches, std::terminate is called and the program aborts.

    Worked example

    Integer division by zero is undefined behaviour in C++, not an automatic exception, so unlike Java there is nothing to catch unless the divisor is tested and the exception thrown deliberately.

    #include <iostream>
    #include <fstream>
    #include <stdexcept>
    #include <string>
    
    // RAII, so cleanup happens without a finally block.
    class LogFile {
        std::ofstream out;
    public:
        explicit LogFile(const std::string& name) : out(name) {
            std::cout << "Log opened\n";
        }
        ~LogFile() { std::cout << "Log closed, resources released\n"; }
        void write(const std::string& msg) { out << msg << "\n"; }
    };
    
    int divide(int a, int b) {
        if (b == 0)
            throw std::runtime_error("cannot divide by zero");   // raised on purpose
        return a / b;
    }
    
    int main() {
        int a = 10, b = 0;
    
        try {
            LogFile log("run.txt");                 // acquired inside the try block
            log.write("starting division");
            std::cout << "Result: " << divide(a, b) << "\n";
            std::cout << "This line is never reached\n";
        }
        catch (const std::runtime_error& e) {       // caught by const reference
            std::cout << "Exception caught: " << e.what() << "\n";
        }
        catch (const std::exception& e) {           // broader net, written after the narrower one
            std::cout << "Other failure: " << e.what() << "\n";
        }
    
        std::cout << "Program continues normally.\n";
        return 0;
    }
    

    Output:

    Log opened
    Log closed, resources released
    Exception caught: cannot divide by zero
    Program continues normally.
    

    What the example shows

    divide checks its divisor and throws std::runtime_error when it is zero, since C++ would otherwise walk straight into undefined behaviour. The try block is abandoned at that point, so the "never reached" line does not print. Before the handler is entered, the LogFile object created inside the block is destroyed, which is why the closing message appears first in the output: the file is already closed by the time the error is reported, and not one line of cleanup code had to be written at the call site.

    The handler prints the description carried by the exception through e.what(). Handlers are ordered from the most derived type to the most general, because the first match wins and a base class handler written first would swallow everything. Each one takes its argument by const reference, since catching by value would slice the derived part off the exception object.

    Because the exception was handled, the program does not abort. Execution resumes after the last handler and the final line prints normally.

    Why this matters

    Exception handling keeps a fault from ending the process, reports the reason in terms a user can act on, and keeps the success path free of an error test after every call. Combined with destructors that release what they acquired, it also guarantees that files, locks, and memory are given back on the failure path as reliably as on the normal one.

  12. 125 marksText file reading and writingAnswer

    Write a program that writes the contents of file 1 into file 2. [5]

    --- Step Function Used Purpose ----------------------------- Open file1 fopen("file1.txt", "r") Opens file1 in read mode Open file2 fopen("file2.txt", "w") Opens file2 in write mode (creates if not exists) Read character fgetc(file1) Rea...