OOP - Object Oriented Programming, Past Papers

Object Oriented Programming BSCS 2nd Term 2015 Past Paper UOS

University of Sargodha 2015 BS 2nd Term Exam Paper for Object Oriented Programming CMP:2124, including key questions on encapsulation, inheritance, polymorphism, operator overloading, and class templates

University of Sargodha
BS 2nd Term Examination 2015

Subject: Computer Science
Paper: Object Oriented Programming (CMP:2124)

Time Allowed: 2:30 Hours
Maximum Marks: 60

Objective Part (Compulsory)

Q.No. 1: Attempt all parts and each require answer 2 – 3 lines (12*2=24)

  1. What is Object-oriented programming?
  2. Explain Encapsulation concept in Object-oriented programming.
  3. What is an abstract class?
  4. Write the syntax of class declaration.
  5. Which Member functions do not needed to be called by object and why?
  6. What is the purpose of Destructor?
  7. Different between method overriding and method overloading?
  8. Define Inheritance?
  9. What are Friend functions? Write the syntax of declaring a friend function.
  10. What is dynamic binding or late binding?
  11. What is the purpose of try and catch blocks?
  12. What is an object?

Subjective Part (4*9=36)

Q. No. 2
Write a class car that contains attributes of car’s name (type string), top speed (type float) and model name (type string). A Constructor with no arguments initializes the data members and two member functions to input and display these attributes.

Q. No. 3
Define Shape class and two subclasses of it, Rectangle and Oval. Use draw function to demonstrate polymorphic behavior by using these classes.

Q. No. 4
What is operator overloading? Overload insertion and extraction operator for a time class.

Q. No. 5
Imagine a tollbooth with a class called Tollbooth that has attributes total_number_of_cars (int) and total_amount (double). Write down a two parameter constructor and an Input member function in this class. Read two objects and store into a text file “tollbooth.txt”.

Q. No. 6
Describe the function template and class template. Discuss with the help of an example.

Q. No. 7
Explain following with example
i. Polymorphism
ii. Dynamic Memory Management

Solved answers – OOP 2015

Short questions

  1. Object-oriented programming is a programming approach that organizes software around objects – units that combine data and the functions that operate on it – using classes, encapsulation, inheritance and polymorphism.
  2. Encapsulation bundles data and functions into a class and hides the data (private members) so it can only be changed through public member functions, protecting it from invalid use.
  3. An abstract class contains at least one pure virtual function (virtual void draw() = 0;); it cannot be instantiated and is used only as a base class.
  4. Syntax of class declaration:
    class Box {
    public:              // access specifier
        double length;   // data members
        double width;
        double area() { return length * width; }   // member function
    };                   // semicolon is required
  5. Static member functions do not need an object; they are called with the class name (Student::getCount()) because they belong to the class as a whole and can only use static members (they have no this pointer).
  6. A destructor (~ClassName()) is called automatically when an object is destroyed to release resources such as dynamically allocated memory or open files.
  7. Overloading: same name, different parameters, same scope, compile time. Overriding: derived class redefines a base-class function with the same signature, needs inheritance, run time (virtual).
  8. Inheritance: creating a new class (derived) from an existing class (base) so that it reuses and extends the base class’s members; models an “is-a” relationship.
  9. A friend function is a non-member function that is allowed to access a class’s private and protected members.
    class Box {
        double width;
    public:
        friend void printWidth(Box b);   // declaration inside the class
    };
    void printWidth(Box b) { cout << b.width; }   // can access private width
  10. Dynamic (late) binding: the function to call is decided at run time according to the actual object type, achieved with virtual functions called through base-class pointers or references.
  11. try encloses code that may throw an exception; catch handles a thrown exception of a matching type, so the program can recover instead of crashing.
  12. An object is an instance of a class; it occupies memory, has its own values for the data members and can call the class’s member functions.

Subjective questions (programs compiled and tested with g++)

Q.2 Car class

#include <iostream>
#include <string>
using namespace std;

class Car {
private:
    string name;
    float topSpeed;
    string model;
public:
    Car() : name(""), topSpeed(0.0f), model("") {}   // no-argument constructor

    void input() {
        cout << "Enter car name: ";   getline(cin, name);
        cout << "Enter top speed: ";  cin >> topSpeed;
        cin.ignore();
        cout << "Enter model name: "; getline(cin, model);
    }
    void display() const {
        cout << "Car: " << name << ", Top speed: " << topSpeed
             << " km/h, Model: " << model << endl;
    }
};

int main() {
    Car c;
    c.input();
    c.display();
    return 0;
}

Q.3 Shape, Rectangle and Oval – polymorphism

#include <iostream>
using namespace std;

class Shape {
public:
    virtual void draw() const { cout << "Drawing a generic shape" << endl; }
    virtual ~Shape() {}
};

class Rectangle : public Shape {
public:
    void draw() const { cout << "Drawing a rectangle" << endl; }
};

class Oval : public Shape {
public:
    void draw() const { cout << "Drawing an oval" << endl; }
};

int main() {
    Shape* shapes[3] = { new Shape, new Rectangle, new Oval };
    for (int i = 0; i < 3; i++) {
        shapes[i]->draw();        // same call, different behaviour
        delete shapes[i];
    }
    return 0;
}

Output: Drawing a generic shape / Drawing a rectangle / Drawing an oval – one draw() call through a Shape* behaves differently for each object.

Q.4 Operator overloading means giving an existing operator a meaning for a user-defined type. Insertion (<<) and extraction (>>) are overloaded as friend functions because the left operand is a stream, not a Time object:

#include <iostream>
using namespace std;

class Time {
private:
    int hours, minutes, seconds;
public:
    Time() : hours(0), minutes(0), seconds(0) {}

    friend ostream& operator<<(ostream& out, const Time& t) {
        out << t.hours << ":" << t.minutes << ":" << t.seconds;
        return out;
    }
    friend istream& operator>>(istream& in, Time& t) {
        in >> t.hours >> t.minutes >> t.seconds;
        return in;
    }
};

int main() {
    Time t;
    cout << "Enter hours minutes seconds: ";
    cin >> t;                       // overloaded >>
    cout << "Time is " << t << endl;  // overloaded <<
    return 0;
}

Input 10 45 30 → “Time is 10:45:30”.

Q.5 Tollbooth class writing to a file

#include <iostream>
#include <fstream>
using namespace std;

class Tollbooth {
private:
    int totalCars;
    double totalAmount;
public:
    Tollbooth(int cars = 0, double amount = 0.0)
        : totalCars(cars), totalAmount(amount) {}

    void input() {
        cout << "Enter total cars and total amount: ";
        cin >> totalCars >> totalAmount;
    }
    void writeTo(ofstream& file) const {
        file << totalCars << " " << totalAmount << endl;
    }
};

int main() {
    Tollbooth t1, t2(0, 0.0);
    t1.input();
    t2.input();

    ofstream file("tollbooth.txt");
    if (!file) { cout << "File error" << endl; return 1; }
    t1.writeTo(file);
    t2.writeTo(file);
    file.close();
    cout << "Saved to tollbooth.txt" << endl;
    return 0;
}

With inputs 120 6000.5 and 80 4000, tollbooth.txt contains two lines: “120 6000.5” and “80 4000”.

Q.6 Function template and class template: a function template defines one generic function for many data types; a class template defines a generic class whose data types are given when objects are created. Both are compile-time polymorphism and avoid writing the same code for every type.

#include <iostream>
using namespace std;

template <typename T>              // function template
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

template <class T>                 // class template
class Pair {
    T first, second;
public:
    Pair(T a, T b) : first(a), second(b) {}
    T sum() const { return first + second; }
};

int main() {
    cout << getMax(4, 9) << " " << getMax(2.5, 1.5) << endl;   // 9 2.5
    Pair<int> p1(3, 4);
    Pair<double> p2(1.5, 2.25);
    cout << p1.sum() << " " << p2.sum() << endl;               // 7 3.75
    return 0;
}

Q.7(i) Polymorphism: “many forms” – one interface, different behaviour. Compile-time: function and operator overloading, templates. Run-time: virtual functions overridden in derived classes (see the Shape example in Q.3).

Q.7(ii) Dynamic memory management: allocating memory at run time on the heap with new and releasing it with delete / delete[]. It is needed when the size is known only at run time; forgetting delete causes memory leaks.

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "How many marks? ";
    cin >> n;
    int* marks = new int[n];          // allocate at run time
    int total = 0;
    for (int i = 0; i < n; i++) {
        cin >> marks[i];
        total += marks[i];
    }
    cout << "Average = " << (double)total / n << endl;
    delete[] marks;                   // free the memory
    return 0;
}

Input 4 marks 70 80 90 60 → Average = 75.

Answers prepared by Shining Study for revision. Check them against your class notes and teacher’s guidance.

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.