2080.1

CSC166 · TU past paper

Object Oriented Programming 2080.1 question paper

The complete TU 2080.1 exam paper for Object Oriented Programming (CSC166), all 12 questions with solved model answers written to the mark scheme.

Tap a question to open its answer.

  1. 110 marksOverloading unary and binary operatorAnswer

    Write a program to create a class named height with data members meter(int) and centimeter(int). Overload the binary + operator using friend function to add two heights.[10]

    Binary Operator Overloading occurs when an operator works on two operands. When overloaded using a friend function, the function is not a member of the class but has access to all private and protected members of the class. A friend func...

  2. 210 marksInitialization of class objectsAnswer

    What is destructor? List its characteristics. Explain the use of default copy constructor with an appropriate example.[10]

    Destructor, Its Characteristics, and Default Copy Constructor


    1. Destructor (Definition)

    A destructor is a special member function of a class that destructs or deletes an object and performs cleanup operations (such as releasing memory) when the object is no longer needed.

    When is a Destructor Called?

    A destructor is called automatically when:

    • The function ends (object goes out of scope of a function)
    • The program ends
    • A block containing local variables ends
    • The delete operator is called on a dynamically allocated object

    2. Characteristics of Destructor

    #Characteristic
    1The destructor has the same name as the class, preceded by a tilde symbol (~)
    2Destructors do not take any arguments (cannot be overloaded)
    3Destructors do not return any value (not even void)
    4There can be only one destructor in a class
    5It is called automatically when the object goes out of scope or is deleted
    6It is typically used to free dynamically allocated memory and release resources
    7It should be declared in the public section of the class

    3. Example of Destructor

    #include <iostream>
    #include <string.h>
    using namespace std;
    
    class String {
    private:
        char *s;
        int size;
    
    public:
        String(char *c) {           // Constructor
            size = strlen(c);
            s = new char[size + 1];
            strcpy(s, c);
            cout << "Constructor called. String: " << s << endl;
        }
    
        ~String() {                 // Destructor
            delete[] s;             // Free dynamically allocated memory
            cout << "Destructor called. Memory freed." << endl;
        }
    };
    
    int main() {
        String str("Hello");        // Constructor is called here
        // Destructor is called automatically when str goes out of scope
        return 0;
    }
    

    Output:

    Constructor called. String: Hello
    Destructor called. Memory freed.
    

    4. Default Copy Constructor

    Definition

    A copy constructor is a special constructor that creates a new object as a copy of an existing object of the same class. When the programmer does not define a copy constructor explicitly, C++ automatically provides a default copy constructor.

    The default copy constructor performs a member-wise (shallow) copy of all data members from one object to another.

    Syntax

    ClassName (const ClassName &old_object);
    

    How the Default Copy Constructor Works

    • It copies each data member of the source object directly into the corresponding data member of the new object.
    • This is called a shallow copy because it copies values as-is, including pointer addresses (not the data pointed to).

    When is the Copy Constructor Invoked?

    1. When an object is initialized with another object of the same class
    2. When an object is passed by value to a function
    3. When an object is returned by value from a function

    5. Example: Default Copy Constructor

    #include <iostream>
    using namespace std;
    
    class Student {
    private:
        int rollNo;
        float marks;
    
    public:
        // Parameterized Constructor
        Student(int r, float m) {
            rollNo = r;
            marks = m;
        }
    
        void display() {
            cout << "Roll No: " << rollNo
                 << ", Marks: " << marks << endl;
        }
    };
    
    int main() {
        Student s1(101, 85.5);      // Original object created using constructor
    
        Student s2 = s1;            // Default copy constructor is called here
                                    // s2 is a copy of s1
    
        cout << "Object s1 -> ";
        s1.display();
    
        cout << "Object s2 -> ";
        s2.display();
    
        return 0;
    }
    

    Output:

    Object s1 -> Roll No: 101, Marks: 85.5
    Object s2 -> Roll No: 101, Marks: 85.5
    

    Explanation

    StepWhat Happens
    Student s1(101, 85.5)Parameterized constructor is called; s1.rollNo = 101, s1.marks = 85.5
    Student s2 = s1Default copy constructor is invoked; copies rollNo and marks from s1 to s2
    Both s1 and s2 display the same valuesMember-wise copy was successful

    6. Limitation of Default Copy Constructor (Shallow Copy Problem)

    When a class contains pointer members, the default copy constructor copies only the address of the pointer, not the actual data. This means both objects point to the same memory location, which can cause problems (double deletion, data corruption). In such cases, a user-defined copy constructor performing a deep copy is required.

    s1.ptr -----> [Memory Block]
    s2.ptr -----> [Same Memory Block]   <-- Problem!
    

    Summary Table

    FeatureDestructorDefault Copy Constructor
    PurposeCleans up / frees resourcesCreates a copy of an object
    Symbol~ClassName()ClassName(const ClassName &obj)
    ArgumentsNoneReference to same class object
    Return typeNoneNone
    Count per classOnly oneOnly one (default)
    Called automaticallyYes, on scope exitYes, on object copy/pass by value
  3. 310 marksA Simple Class and ObjectAnswer

    Write a program to realize the above hierarchy. Create necessary member functions (constructor) to initialize and display necessary information.[10]

    Based on the reference context, we need to create a hierarchy where a derived class inherits from a base class, and use constructors to initialize and display member variables of both classes. --- --- --- --- Concept Description ------ B...

  4. 45 marksObject oriented programming approachAnswer

    Define object. What are the benefits of Object Oriented Programming Language? [5]

    Object and Benefits of Object Oriented Programming Language


    Definition of Object

    An object is a basic run-time entity in an object-oriented system. Objects are variables (instances) of a user-defined data type called a class. They contain both data and code to manipulate that data.

    "Objects are the basic run-time entities in an object-oriented system... In fact, objects are variables of the type class."

    Key characteristics of an object:

    • Objects take up space in memory and have an associated address (like structures or unions in C).
    • When a program is executed, objects interact by sending messages to one another.
    • Program objects are chosen such that they match closely with real-world objects.

    Example:

    class person {
        char name[20];
        int age;
    public:
        void getdetails() { }
    };
    
    int main() {
        person p1;   // p1 is an object of class person
    }
    

    Here, p1 is an object of class person that holds its own copy of name and age.


    Benefits of Object Oriented Programming (OOP)

    FeatureBenefit
    Data Hiding / SecurityOOP provides access specifiers (private, public, protected) to restrict access to data, making programs more secure. Procedural languages lack this.
    Modularity (Objects)Programs are divided into small, manageable units called objects, making code easier to understand and maintain.
    Easy to Add New Data and FunctionsAdding new data members and member functions to a class is easy without disturbing the rest of the program. In procedural programming, adding new data requires revising all functions that access it.
    OverloadingOOP supports function and operator overloading, allowing the same name to be used for different purposes, which is not possible in procedural-oriented programming.
    Real-World ModelingOOP is based on real-world entities, making it easier to model and solve real-world problems. Procedural programming is action-oriented and does not model real-world problems well.
    Bottom-Up ApproachOOP follows a bottom-up approach, which is more systematic for designing large and complex programs.
    Reusability (Inheritance)Classes can be reused and extended through inheritance, reducing redundancy and saving development time.

    Summary

    In short, OOP overcomes the major drawbacks of procedural programming by providing security through data hiding, real-world modeling, easy extensibility, and code reusability, making it the preferred approach for developing large-scale, maintainable software systems.

  5. 55 marksType ConversionAnswer

    Explain the significance of type conversion. How do we achieve dynamic memory allocation in C++? Explain with an example. [5]

    --- Type conversion (typecasting) refers to changing an entity of one data type into another data type. It is used in computer programming to ensure variables are correctly processed by a function. - Ensures compatibility between differe...

  6. 65 marksData ConversionAnswer

    Create two classes Rupee and Dollar respectively. Write conversion operator to convert between Rupee and Dollar assuming that 1 dollar equals 133 rupees. Write a main program that allows the user to enter an amount in either currency and then converts it to other currency and displays the result. [5]

    This problem uses type conversion between class objects using a conversion operator (casting operator) defined inside the source class. The conversion operator converts an object of one class type to another class type. Rate: 1 Dollar = ...

  7. 75 marksPolymorphism and its rolesAnswer

    Difference between compile time and run time polymorphism. [5]

    Polymorphism means that the same thing or name exists in many forms to perform various actions. In C++, it is classified into two types: --- - Achieved using function overloading and operator overloading. - The compiler directly associat...

  8. 85 marksFunction templatesAnswer

    Explain function template overloading with suitable example. [5]

    Function template overloading means defining more than one template function with the same name but with different numbers of parameters or different logic, so that the compiler selects the appropriate version based on the arguments pass...

  9. 95 marksFile Input/output with StreamsAnswer

    Write a program that stores information of employees in a file and displays the file's content in ascending order of their salary. [5]

    Ofstream is used to write information to a file, and ifstream is used to read information from a file. The header <fstream must be included. After reading all employee records back from the file, we sort them by salary in ascending order...

  10. 105 marksObjects as Function ArgumentsAnswer

    What is the benefit of passing object as arguments? Write a program to create a class named actor with data members name and rating. Initialize the data members and display those names whose rating is greater than 5 using the concept of constant object. [5]

    As stated in the notes, passing objects as arguments to member functions is useful in the following ways: - Initialization of data members: When we want to initialize all data members of one object with another object, we can pass object...

  11. 115 marksAccess SpecifiersAnswer

    Explain the practical implication of protected specifier in inheritance. List advantages and disadvantages of inheritance. [5]

    "Protected access specifier is similar to that of private access specifiers, the difference is that the class member declared as protected are inaccessible outside the class but they can be accessed by any subclass (derived class) of tha...

  12. 125 marksThis pointerAnswer

    Write short notes on: a. This pointer b. ios member function [5]

    --- In C++, this is a special implicit pointer that is automatically passed to every non-static member function of a class. It holds the address of the object that invokes the member function. - When a member function is called on an obj...