OOP - Object Oriented Programming, Past Papers

Object Oriented Programming BSCS 2nd Term 2020 Past Paper UOS

OOP Past Paper 2020 UOS

University of Sargodha (UOS) BS Computer Science 2nd term Object Oriented Programming (CMPC-102) past paper 2020, with the full question paper in text form and solved answers to every short and long question. All C++ programs are tested.

OOP Past Paper 2020 (text version)

University of Sargodha – BS 2nd Semester/Term Examination 2020, Computer Science
Paper: Object Oriented Programming (CMPC-102) · Time: 2:30 hours · Maximum marks: 60
Note: Objective part is compulsory. Attempt any three questions from the subjective part.

Objective part (compulsory) – short answers in 2–3 lines

  1. Differentiate between function overloading and function overriding.
  2. What is the purpose of information hiding?
  3. Give an example of exception catching.
  4. Give an example of any overloaded operator of the string class.
  5. How do you differentiate a class from an object?
  6. Why do we use a friend function?
  7. What happens in case a user does not provide a constructor?
  8. Can sorting help in searching the elements of an array?
  9. Can a constructor call another constructor using the this keyword? Give an example.
  10. What are containers and iterators used for?
  11. When do we need to allocate memory dynamically?
  12. How many destructors can be defined in a class? Argue with reasoning.

Subjective part (attempt any three, 3 × 12)

  • Q.2 Create a class Rectangle with attributes length and width, each set to 1 by the constructor. Provide member functions that calculate the perimeter and the area of the rectangle. Also provide set and get functions for length and width, and a function to print it. The set functions should verify that length and width are floating-point numbers larger than 0.0 and less than 20.0.
  • Q.3 (a) Write a detailed note on inheritance. Also clearly mention the relationship between base class and derived class. (b) Differentiate between virtual functions and pure virtual functions.
  • Q.4 (a) Compare in detail the access modifiers public, private and protected. (b) Write a simple program that overloads the unary prefix and postfix ++ and −− operators.
  • Q.5 Create a Distance class with instance variables feet and inches. Write a suitable parameterized constructor, getter and setter functions. Also write a function to add two Distance objects so that if the resulting inches exceed 12, feet is incremented by 1 and inches decremented by 12, using the statement dist3.add(dist1, dist2).
  • Q.6 Define a class for a bank account with data members: name of depositor, account number, type of account and balance. Member functions: (a) a constructor to assign initial default values; (b) a constructor to assign values from the user; (c) a deposit function that shows an error and does not add the amount if it is less than or equal to 0; (d) a withdraw function that shows an error if the amount is greater than the balance or negative.

Solved answers – OOP 2020

Short questions

  1. Overloading: same function name with different parameter lists in the same scope; resolved at compile time. Overriding: a derived class redefines a base-class (virtual) function with the same signature; resolved at run time.
  2. Information hiding keeps a class’s internal data and implementation private, exposing only a public interface. It protects data from invalid changes and lets the implementation change without affecting other code.
  3. Exception catching with try/throw/catch:
    try {
        int d = 0;
        if (d == 0) throw runtime_error("Division by zero");
        cout << 10 / d;
    } catch (const runtime_error& e) {
        cout << "Caught: " << e.what() << endl;   // Caught: Division by zero
    }
  4. The string class overloads + for joining: string s = s1 + " " + s2; (others: ==, +=, [], <<).
  5. A class is a blueprint that defines data members and functions and takes no memory for data by itself; an object is an instance of the class with its own copy of the data, e.g. Car c1;
  6. A friend function is used when a non-member function needs access to private/protected members, e.g. overloading << for output or a function working on two classes’ private data.
  7. If no constructor is written, the compiler provides an implicit default constructor. It does not initialize built-in members (they hold garbage values) but calls the default constructors of class-type members such as string.
  8. Yes. In a sorted array we can use binary search, which takes O(log n) comparisons instead of O(n) for linear search – e.g. 1,000 elements need at most 10 comparisons.
  9. Not with this in C++ (that is Java’s this(...)). Since C++11 a constructor can call another one through a delegating constructor in the initializer list:
    class Box {
        int l, w;
    public:
        Box(int a, int b) : l(a), w(b) {}
        Box() : Box(1, 1) {}      // calls the other constructor
    };
  10. Containers (vector, list, map, set) are STL classes that store collections of objects; iterators are pointer-like objects used to traverse and access container elements, e.g. for (auto it = v.begin(); it != v.end(); ++it).
  11. When the amount of memory is known only at run time (e.g. array size entered by the user), when an object must outlive the function that creates it, or for dynamic structures such as linked lists and trees – using new and delete.
  12. Only one. A destructor takes no arguments and returns nothing, so it cannot be overloaded – there would be no way to distinguish two versions, and the object is destroyed only once.

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

Q.2 Rectangle class (the paper says “larger than 20.0”; the intended range is greater than 0.0 and less than 20.0)

#include <iostream>
using namespace std;

class Rectangle {
private:
    float length, width;
public:
    Rectangle() : length(1.0f), width(1.0f) {}   // both start at 1

    // valid range: greater than 0.0 and less than 20.0
    void setLength(float l) {
        if (l > 0.0f && l < 20.0f) length = l;
        else cout << "Invalid length " << l << endl;
    }
    void setWidth(float w) {
        if (w > 0.0f && w < 20.0f) width = w;
        else cout << "Invalid width " << w << endl;
    }
    float getLength() const { return length; }
    float getWidth() const { return width; }

    float area() const { return length * width; }
    float perimeter() const { return 2 * (length + width); }

    void print() const {
        cout << "Length = " << length << ", Width = " << width
             << ", Area = " << area() << ", Perimeter = " << perimeter() << endl;
    }
};

int main() {
    Rectangle r;
    r.print();            // 1, 1, area 1, perimeter 4
    r.setLength(7.5f);
    r.setWidth(4.0f);
    r.print();            // area 30, perimeter 23
    r.setWidth(25.0f);    // rejected
    return 0;
}

Q.3(a) Inheritance: a mechanism by which a new class (derived/child) acquires the data members and functions of an existing class (base/parent), adding or redefining features. It models an is-a relationship (a Car is a Vehicle), promotes code reuse and supports polymorphism. Syntax: class Derived : public Base { … };. Types: single, multiple, multilevel, hierarchical and hybrid. The derived class can access public and protected members of the base, but not private ones; base constructors run before derived constructors and destructors run in reverse order. The mode of inheritance (public, protected, private) controls how base members appear in the derived class.

Q.3(b) Virtual vs pure virtual functions: a virtual function has a body in the base class and may be overridden; calls through base pointers are resolved at run time. A pure virtual function has no body (virtual void draw() = 0;), must be overridden in derived classes, and makes its class abstract so no objects of it can be created.

Q.4(a) Access modifiers: public – accessible from anywhere (class, derived classes, outside code); used for the interface. private – accessible only inside the class and its friends; the default for class members; used for data hiding. protected – like private for outside code, but accessible in derived classes; used for data the children need.

Q.4(b) Overloading prefix and postfix ++ and −−

#include <iostream>
using namespace std;

class Counter {
private:
    int value;
public:
    Counter(int v = 0) : value(v) {}

    Counter& operator++() {          // prefix ++c
        ++value;
        return *this;
    }
    Counter operator++(int) {        // postfix c++ (dummy int)
        Counter old = *this;
        value++;
        return old;
    }
    Counter& operator--() {          // prefix --c
        --value;
        return *this;
    }
    Counter operator--(int) {        // postfix c--
        Counter old = *this;
        value--;
        return old;
    }
    int get() const { return value; }
};

int main() {
    Counter c(5);
    Counter a = ++c;   // c = 6, a = 6
    Counter b = c++;   // b = 6, c = 7
    cout << "a=" << a.get() << " b=" << b.get() << " c=" << c.get() << endl;
    Counter d = --c;   // c = 6, d = 6
    Counter e = c--;   // e = 6, c = 5
    cout << "d=" << d.get() << " e=" << e.get() << " c=" << c.get() << endl;
    return 0;
}

Output: a=6 b=6 c=7, then d=6 e=6 c=5. The postfix versions take a dummy int parameter and return the old value.

Q.5 Distance class

#include <iostream>
using namespace std;

class Distance {
private:
    int feet;
    float inches;
public:
    Distance(int f = 0, float i = 0.0f) : feet(f), inches(i) {}

    void setFeet(int f) { feet = f; }
    void setInches(float i) { inches = i; }
    int getFeet() const { return feet; }
    float getInches() const { return inches; }

    void add(const Distance& d1, const Distance& d2) {
        feet = d1.feet + d2.feet;
        inches = d1.inches + d2.inches;
        if (inches >= 12.0f) {      // carry 12 inches into 1 foot
            feet++;
            inches -= 12.0f;
        }
    }
    void show() const { cout << feet << "' " << inches << "\"" << endl; }
};

int main() {
    Distance dist1(5, 8.5f), dist2(3, 6.0f), dist3;
    dist3.add(dist1, dist2);
    dist3.show();      // 9' 2.5"
    return 0;
}

5′ 8.5″ + 3′ 6″ = 8′ 14.5″ → 9′ 2.5″.

Q.6 Bank account class

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

class BankAccount {
private:
    string name;
    long accountNo;
    string type;
    double balance;
public:
    BankAccount() : name("Unknown"), accountNo(0), type("Saving"), balance(0.0) {}

    BankAccount(string n, long no, string t, double b)
        : name(n), accountNo(no), type(t), balance(b) {}

    void deposit(double amount) {
        if (amount <= 0) {
            cout << "Error: deposit must be greater than 0" << endl;
            return;
        }
        balance += amount;
    }
    void withdraw(double amount) {
        if (amount < 0) {
            cout << "Error: amount cannot be negative" << endl;
        } else if (amount > balance) {
            cout << "Error: insufficient balance" << endl;
        } else {
            balance -= amount;
        }
    }
    void display() const {
        cout << name << " (" << accountNo << ", " << type << ") Balance: " << balance << endl;
    }
};

int main() {
    BankAccount a;                                   // default values
    a.display();

    string n, t; long no; double b;
    cout << "Enter name, account no, type, balance: ";
    cin >> n >> no >> t >> b;
    BankAccount acc(n, no, t, b);                    // values from user
    acc.deposit(0);          // error
    acc.deposit(1500);
    acc.withdraw(-50);       // error
    acc.withdraw(100000);    // error
    acc.withdraw(500);
    acc.display();
    return 0;
}

Sample run with “Ali 1001 Saving 5000”: the three invalid operations print errors and the final balance is 6000.

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.