2079

CSC166 · TU past paper

Object Oriented Programming 2079 question paper

The complete TU 2079 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 marksAggregationAnswer

    What is aggregation? Write a program for implementing following: Create a class author with attributes name and qualification. Also create a class publication with name. Form these classes to derive a class book having attribute title and price. Each of three classes should have a getdata() method to get their data from user. The classes should have putdata() method to display the data. Create instances of the class book in main.[10]

    Aggregation is a special form of association in Object-Oriented Programming where one class contains objects of other classes as its members, but the contained objects can exist independently of the container class. It represents a "has-...

  2. 210 marksInitialization of class objectsAnswer

    What is the use of constructor and destructor? Write a program for illustrating default constructor, parameterized constructor and copy constructor.[10]

    Constructor and Destructor in C++


    Use of Constructor

    A constructor is a special member function of a class that is automatically called when an object is created. Its main uses are:

    • Automatic initialization of data members when an object is created
    • Eliminates the need to manually initialize each object
    • Useful when handling arrays of objects (e.g., initializing 100s of Person objects with default age = 0)
    • Executes code immediately after an object is created
    • Has the same name as the class, no return type, and can be overloaded

    Use of Destructor

    A destructor is a member function that destructs or deletes an object and frees resources. Its main uses are:

    • Automatically releases memory or resources when an object goes out of scope
    • Called automatically when:
      • A function ends
      • The program ends
      • A block containing local variables ends
      • The delete operator is called
    • Has the same name as the class preceded by ~
    • Takes no arguments and returns nothing
    • There can be only one destructor in a class

    Program: Illustrating Default, Parameterized, and Copy Constructor

    #include<iostream.h>
    #include<conio.h>
    
    class Student {
        private:
            int rollNo;
            float marks;
    
        public:
            // 1. Default Constructor
            // Called automatically when no arguments are passed
            Student() {
                rollNo = 0;
                marks  = 0.0;
                cout << "Default Constructor called" << endl;
            }
    
            // 2. Parameterized Constructor
            // Called when arguments are passed during object creation
            Student(int r, float m) {
                rollNo = r;
                marks  = m;
                cout << "Parameterized Constructor called" << endl;
            }
    
            // 3. Copy Constructor
            // Called when one object is initialized with another object
            Student(Student &s) {
                rollNo = s.rollNo;
                marks  = s.marks;
                cout << "Copy Constructor called" << endl;
            }
    
            // Destructor
            ~Student() {
                cout << "Destructor called for Roll No: " << rollNo << endl;
            }
    
            // Display function
            void display() {
                cout << "Roll No : " << rollNo << endl;
                cout << "Marks   : " << marks  << endl;
            }
    };
    
    void main() {
        clrscr();
    
        // Calls Default Constructor
        cout << "--- Object s1 (Default Constructor) ---" << endl;
        Student s1;
        s1.display();
    
        // Calls Parameterized Constructor
        cout << "\n--- Object s2 (Parameterized Constructor) ---" << endl;
        Student s2(101, 85.5);
        s2.display();
    
        // Calls Copy Constructor
        cout << "\n--- Object s3 (Copy Constructor) ---" << endl;
        Student s3(s2);
        s3.display();
    
        getch();
    }
    

    Output

    --- Object s1 (Default Constructor) ---
    Default Constructor called
    Roll No : 0
    Marks   : 0
    
    --- Object s2 (Parameterized Constructor) ---
    Parameterized Constructor called
    Roll No : 101
    Marks   : 85.5
    
    --- Object s3 (Copy Constructor) ---
    Copy Constructor called
    Roll No : 101
    Marks   : 85.5
    
    Destructor called for Roll No: 101
    Destructor called for Roll No: 101
    Destructor called for Roll No: 0
    

    Summary Table

    Constructor TypeWhen CalledArguments
    Default ConstructorStudent s1;None
    Parameterized ConstructorStudent s2(101, 85.5);One or more
    Copy ConstructorStudent s3(s2);Reference to same class object
    DestructorObject goes out of scopeNone

    Note: Destructors are called in reverse order of object creation, as shown in the output above.

  3. 310 marksFundamental of operator overloadingAnswer

    What is operator overloading? Why it is necessary to overload and operator? Write a program for overloading comparison operators.[10]

    "The method of making operators to work for user defined class and having the ability to provide operators with a special user defined meaning is known as operator overloading." In simple terms, operator overloading allows us to redefine...

  4. 45 marksA Simple Class and ObjectAnswer

    Define class and object with suitable examples. How members of class can be accessed? [5]

    A class is a user-defined data type that contains data members and member functions together. It acts as a blueprint or template for creating objects. Like structures and unions in C, a class groups related data and functions, but adds t...

  5. 55 marksCharacteristics of object oriented languagAnswer

    Describe the characteristics of object oriented programming languages. [5]

    Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around objects rather than functions and logic. The key characteristics (terms) of OOP are described below: --- - Objects are the basic run-time e...

  6. 65 marksFunctionsAnswer

    What is inline function? Why it is used? Write a program to illustrate inline function. [5]

    Inline Function in C++

    Definition

    An inline function is a C++ enhancement feature in which the compiler replaces the function call with the actual body (definition) of the function at compile time, instead of making a regular function call at runtime.

    To declare an inline function, the keyword inline is placed before the function definition.

    Syntax:

    inline return_type function_name(parameters) {
        // function body
    }
    

    Why Inline Functions are Used

    As stated in the notes:

    "The inline functions are a C++ enhancement feature to increase the execution time of a program. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime."

    The main reasons for using inline functions are:

    • To increase execution speed: Eliminates the overhead of a function call (saving/restoring registers, jumping to function address, etc.)
    • To avoid function call overhead: The function body is directly substituted at the point of call during compilation.
    • Useful for small, frequently called functions: Where the overhead of a call is significant compared to the function body itself.
    • Maintains readability: Code remains modular and readable like normal functions, but executes like direct code.

    Program to Illustrate Inline Function

    #include<iostream>
    using namespace std;
    
    // Inline function to calculate square of a number
    inline int square(int x) {
        return x * x;
    }
    
    // Inline function to calculate cube of a number
    inline int cube(int x) {
        return x * x * x;
    }
    
    int main() {
        int num;
        cout << "Enter a number: ";
        cin >> num;
    
        // Compiler replaces these calls with actual code at compile time
        cout << "Square of " << num << " = " << square(num) << endl;
        cout << "Cube of "   << num << " = " << cube(num)   << endl;
    
        return 0;
    }
    

    Sample Output

    Enter a number: 4
    Square of 4 = 16
    Cube of 4 = 64
    

    How It Works

    When the compiler encounters square(num), instead of making a function call at runtime, it substitutes the code as:

    // square(num) is replaced by:
    num * num
    

    This substitution happens at compile time, making execution faster by removing function call overhead.


    Key Points to Remember

    FeatureInline Function
    Keyword usedinline
    Substitution timeCompile time
    PurposeIncrease execution speed
    Best used forSmall, frequently called functions
    Overhead removedFunction call overhead
  7. 75 marksData ConversionAnswer

    What are possible data conversion types? Write a program to show basis to user defined conversion. [5]

    Data Conversion Types and User-Defined Conversion

    Possible Data Conversion Types

    In C++, there are mainly two types of data conversion:


    1. Implicit Conversion (Automatic Type Conversion)

    • Done automatically by the compiler without any external trigger from the user.
    • Takes place when there is more than one data type in an expression.
    • All data types are upgraded to the largest data type present in the expression to avoid loss of data.

    Example:

    int a = 5;
    float b = 2.5;
    float result = a + b;  // int 'a' is automatically converted to float
    

    2. Explicit Conversion (User-Defined / Type Casting)

    • Also called type casting.
    • The user manually converts the data type of a value to a desired type.
    • In C++, it can be done in two ways:
      • Using C-style cast: (type) expression
      • Using C++ cast operator: type(expression)

    Program to Show Basic to User-Defined Conversion

    The following program demonstrates converting a basic (built-in) data type to a user-defined data type (class) using a constructor, and converting a user-defined type back to a basic type using a conversion function (operator overloading).

    #include<iostream>
    using namespace std;
    
    // User-defined class
    class Celsius {
        float temperature;
    
    public:
        // Default constructor
        Celsius() {
            temperature = 0;
        }
    
        // Constructor for basic to user-defined conversion
        // Converts float (basic type) to Celsius object (user-defined type)
        Celsius(float t) {
            temperature = t;
            cout << "Basic to User-Defined Conversion: float -> Celsius object" << endl;
        }
    
        // Conversion function: user-defined to basic type
        // Converts Celsius object to float (basic type)
        operator float() {
            cout << "User-Defined to Basic Conversion: Celsius object -> float" << endl;
            return temperature;
        }
    
        void display() {
            cout << "Temperature = " << temperature << " C" << endl;
        }
    };
    
    int main() {
        float temp = 36.6;
    
        // Basic to User-Defined Conversion
        // float is implicitly converted to Celsius object using constructor
        Celsius c1 = temp;
        c1.display();
    
        // User-Defined to Basic Conversion
        // Celsius object is converted to float using conversion function
        float t2 = c1;
        cout << "Converted back to float: " << t2 << endl;
    
        // Explicit (user-defined) type casting
        Celsius c2(98.4);
        float t3 = (float) c2;   // C-style explicit cast
        cout << "Explicit cast result: " << t3 << endl;
    
        return 0;
    }
    

    Output

    Basic to User-Defined Conversion: float -> Celsius object
    Temperature = 36.6 C
    User-Defined to Basic Conversion: Celsius object -> float
    Converted back to float: 36.6
    Basic to User-Defined Conversion: float -> Celsius object
    User-Defined to Basic Conversion: Celsius object -> float
    Explicit cast result: 98.4
    

    Summary Table

    Conversion TypeDirectionMechanism Used
    Basic to User-Definedfloat -> classConstructor with parameter
    User-Defined to Basicclass -> floatConversion function (operator float())
    Explicit (Type Casting)Any -> Any(type) or type()

    Note: The constructor enables basic-to-user-defined conversion, while the conversion operator (operator overloading) enables user-defined-to-basic conversion. Both together form the complete picture of user-defined type conversion in C++.

  8. 85 marksAccess SpecifiersAnswer

    What are the various class access specifies? How public inheritance differs from private inheritance? [5]

    Class Access Specifiers and Public vs Private Inheritance

    Access Specifiers in C++

    A class uses access specifiers to control the visibility of its data members and member functions. There are three access specifiers in C++:


    1. Private

    • Members declared as private are visible only to member functions of their own class.
    • They cannot be accessed from outside the class or by derived classes directly.
    • If no access specifier is mentioned, members are private by default.
    class Example {
        int x;  // private by default
    private:
        int y;  // explicitly private
    };
    

    2. Protected

    • Members declared as protected are visible to member functions of their own class and derived classes.
    • They cannot be accessed from outside these classes (data hiding is maintained).
    • Useful when inheritance is involved.
    class Example {
    protected:
        int x;  // accessible in derived class
    };
    

    3. Public

    • Members declared as public are visible to all functions in the program.
    • They can be accessed from anywhere using the dot operator (.) with an object.
    class Example {
    public:
        int x;  // accessible from anywhere
    };
    

    Summary Table

    Access SpecifierOwn ClassDerived ClassOutside Class
    privateYesNoNo
    protectedYesYesNo
    publicYesYesYes

    Public Inheritance vs Private Inheritance

    When a derived class inherits from a base class, the mode of inheritance determines how the base class members are accessible in the derived class.


    Public Inheritance

    class Derived : public Base {
        // ...
    };
    
    • public members of Base remain public in Derived.
    • protected members of Base remain protected in Derived.
    • private members of Base are not accessible in Derived.
    • Objects of the derived class can access the public members of the base class.
    • This represents an "is-a" relationship.

    Private Inheritance

    class Derived : private Base {
        // ...
    };
    
    • public members of Base become private in Derived.
    • protected members of Base become private in Derived.
    • private members of Base are not accessible in Derived.
    • Objects of the derived class cannot access any inherited members from outside.
    • This represents a "has-a" (implementation) relationship.

    Comparison Table

    FeaturePublic InheritancePrivate Inheritance
    Base public membersRemain public in DerivedBecome private in Derived
    Base protected membersRemain protected in DerivedBecome private in Derived
    Base private membersNot accessibleNot accessible
    Access via objectAllowedNot allowed
    Relationship"is-a""has-a"

    Example

    class Base {
    public:
        int x;
    protected:
        int y;
    private:
        int z;
    };
    
    class PublicDerived : public Base {
        // x is public, y is protected, z is not accessible
    };
    
    class PrivateDerived : private Base {
        // x is private, y is private, z is not accessible
    };
    
    int main() {
        PublicDerived pd;
        pd.x = 10;   // Allowed (x is public)
    
        PrivateDerived pvd;
        pvd.x = 10;  // ERROR: x is private in PrivateDerived
    }
    

    Key Point: Public inheritance preserves the access levels of base class members, while private inheritance makes all inherited members private, restricting access from outside the derived class.

  9. 95 marksFunction templates with multiple argumentsAnswer

    Write a program to implement function template with multiple arguments. [5]

    A function template allows writing a generic function that works with different data types. When a template uses more than one parameter, it is called a function template with multiple arguments. Syntax: --- --- --- Template Call T1 T2 D...

  10. 105 marksFile Access Pointers and their ManipulatorAnswer

    Write a program to illustrate the use of seekg() and tellg(). [5]

    • tellg() -- Returns the current get pointer position (current read position) in the file as a number of bytes from the beginning. - seekg() -- Moves the get pointer to a specified position in the file so that the next read operation sta...
  11. 115 marksDynamic Memory Allocation with new and delAnswer

    How dynamic memory allocation is done using new and delete? Write program for illustrating use of new and delete. [5]

    The process of allocating memory during runtime (execution time) of a program using the heap space of memory, to reduce wastage of memory, is called dynamic memory allocation. - new - memory allocation operator (allocates memory at runti...

  12. 125 marksFriend function and Static functionAnswer

    Write short note on: a) Friend Function b) Early binding and late binding [5]

    --- A friend function in C++ is a function that is not a member of a class but has the privilege to access the private and protected members of that class. It is declared inside the class using the keyword friend. - It is declared inside...