OOP - Object Oriented Programming, Past Papers, UOS Main Campus

Object Oriented Programming Past Paper 2014 – BSCS 2nd Term UOS (CMP-2124)

ProgramBSCS
Term2nd
Year2014
Course codeCMP-2124
AnswersSolved ✓

University of Sargodha BS Computer Science 2nd term Object Oriented Programming (CMP-2124) paper, 2014 exam, session 2013-17 (60 marks, 2:30 hours). The paper is retyped below, followed by solved answers for all 12 short questions and all six subjective questions with complete C++ programs: class Computer, multiple inheritance (Person, Student, Scholarship), polymorphism with Mother/Boy/Girl, writing objects to BSCS.bin, a Rational class with operator overloading and exceptions, and templates. Every program was compiled and run.

Solved answers

Q1 – Short answers (12 × 2)

i. Object vs class. A class is a blueprint/user-defined type that describes data members and member functions; it uses no memory for data by itself. An object is an instance of a class created in memory with actual values, e.g. class Car vs Car c1;.

ii. Encapsulation. Bundling data and the functions that operate on it into a single unit (class) and hiding the data from outside access using private, so it is accessed only through public member functions (data hiding).

iii. Why keep member functions constant? A const member function (int get() const;) promises not to modify the object’s data. The compiler enforces this, it prevents accidental changes, and only const functions can be called on const objects.

iv. How many destructors? Only one. A destructor (~ClassName()) takes no arguments and has no return type, so it cannot be overloaded.

v. Multiple inheritance and its disadvantage. A class derived from more than one base class: class C : public A, public B. Disadvantage: ambiguity when both bases have members with the same name, and the diamond problem (two copies of a common base), which needs virtual inheritance; it also makes design more complex.

vi. Abstract class. A class with at least one pure virtual function (virtual void draw() = 0;). It cannot be instantiated and is used as a base class that defines an interface for derived classes.

vii. Creating new operators; operators that cannot be overloaded. No – overloading can only give new meaning to existing operators; it cannot create new operators or change precedence/arity. Operators that cannot be overloaded: :: (scope), . (member access), .*, ?: (ternary), sizeof and typeid.

viii. Function overriding. A derived class provides its own definition of a base-class function with the same name, parameters and return type. With virtual in the base, the call is resolved at run time by the object type (polymorphism).

ix. Exception handling. A mechanism to detect and handle run-time errors using try (code that may fail), throw (raise an exception) and catch (handle it), so the program does not crash and error-handling code is separated from normal code.

x. Why binary files are better than text files. Data is stored in the same format as in memory, so no conversion is needed – faster reading/writing, usually smaller size, exact values (no rounding of floats), and whole objects/records can be written with write() and accessed randomly with seekg().

xi. Pure virtual function. A virtual function with no body in the base class, declared with = 0: virtual double area() = 0;. It makes the class abstract and forces every concrete derived class to override it.

xii. Purpose of this pointer. An implicit pointer, available in every non-static member function, that points to the object that called the function. It is used to distinguish members from parameters with the same name (this->x = x;) and to return the current object (return *this;) for chaining.

Q2 – Class Computer

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

class Computer {
    string model;
    float price;
    string type;
public:
    Computer() : model("Not set"), price(0.0f), type("Not set") {}
    void input() {
        cout << "Enter model: ";  getline(cin, model);
        cout << "Enter price: ";  cin >> price;  cin.ignore();
        cout << "Enter type: ";   getline(cin, type);
    }
    void display() const {
        cout << "Model: " << model << "\nPrice: " << price
             << "\nType: " << type << endl;
    }
};

int main() {
    Computer c;
    c.display();      // values set by the no-argument constructor
    c.input();
    c.display();
    return 0;
}

Sample run (input: Dell 5490, 85000.5, Laptop):

Model: Not set
Price: 0
Type: Not set
Enter model: Enter price: Enter type: Model: Dell 5490
Price: 85000.5
Type: Laptop

The no-argument constructor initialises all three data members; input() reads them and display() prints them.

Q3 – Person, Student and Scholarship (multiple inheritance)

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

class Person {
protected:
    string name;
    int age;
public:
    void input() { cout << "Name: "; getline(cin, name); cout << "Age: "; cin >> age; }
    void show() const { cout << "Name: " << name << ", Age: " << age << endl; }
};

class Student {
protected:
    int marks;
public:
    void input() { cout << "Marks: "; cin >> marks; }
    void show() const { cout << "Marks: " << marks << endl; }
};

class Scholarship : public Person, public Student {
    string sname;                       // scholarship name
public:
    void input() {                      // overrides both input() functions
        Person::input();
        Student::input();
        cin.ignore();
        cout << "Scholarship name: "; getline(cin, sname);
    }
    void show() const {                 // overrides both show() functions
        Person::show();
        Student::show();
        cout << "Scholarship: " << sname << endl;
    }
};

int main() {
    Scholarship s;
    s.input();
    s.show();
    return 0;
}

Sample output (input: Ahmed Khan, 21, 78, PEEF):

Name: Ahmed Khan, Age: 21
Marks: 78
Scholarship: PEEF

Scholarship is publicly derived from both Person and Student. Its input() and show() override (hide) the base versions and call them with the scope operator (Person::input(), Student::input()), which also removes the ambiguity between the two inherited functions.

Q4 – Mother, Boy and Girl: polymorphism through a pointer

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

class Mother {
protected:
    int mage;
public:
    Mother(int a = 0) : mage(a) {}
    virtual void iam() { cout << "I am mother and my age is " << mage << endl; }
    virtual ~Mother() {}
};

class Boy : public Mother {
    string name;
public:
    Boy(string n, int motherAge) : Mother(motherAge), name(n) {}
    void iam() override { cout << "I am boy, my name is " << name << endl; }
};

class Girl : public Mother {
    string name;
public:
    Girl(string n, int motherAge) : Mother(motherAge), name(n) {}
    void iam() override { cout << "I am girl, my name is " << name << endl; }
};

int main() {
    Mother m(45);
    Boy b("Ali", 45);
    Girl g("Sara", 45);

    Mother *p;                 // base-class pointer
    p = &m;  p->iam();
    p = &b;  p->iam();         // calls Boy::iam()  (run-time polymorphism)
    p = &g;  p->iam();         // calls Girl::iam()
    return 0;
}

Output:

I am mother and my age is 45
I am boy, my name is Ali
I am girl, my name is Sara

Because iam() is virtual in Mother, the call p->iam() through the base-class pointer is bound at run time to the function of the actual object (dynamic binding) – the same statement produces different behaviour, which is polymorphism. The constructors of Boy and Girl pass the mother’s age to the Mother constructor through the initialiser list.

Q5 – Class BSCS stored in the binary file BSCS.bin

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

class BSCS {
    int year;
    int strength;
    char college[40];          // fixed size so the object can be written as raw bytes
public:
    BSCS(int y = 0, int s = 0, const char *c = "") : year(y), strength(s) {
        strncpy(college, c, sizeof(college) - 1);
        college[sizeof(college) - 1] = '\0';
    }
    void input() {
        cout << "Year: ";     cin >> year;
        cout << "Strength: "; cin >> strength;
        cin.ignore();
        cout << "College: ";  cin.getline(college, sizeof(college));
    }
    void show() const {
        cout << year << "  " << strength << "  " << college << endl;
    }
};

int main() {
    ofstream out("BSCS.bin", ios::binary);
    for (int i = 0; i < 3; i++) {
        BSCS b;
        cout << "Object " << i + 1 << endl;
        b.input();
        out.write(reinterpret_cast<char*>(&b), sizeof(b));
    }
    out.close();

    ifstream in("BSCS.bin", ios::binary);      // read back to check
    BSCS b;
    while (in.read(reinterpret_cast<char*>(&b), sizeof(b)))
        b.show();
    return 0;
}

Sample run (three objects entered) – after writing, the file is read back:

2014  50  UOS Sargodha
2015  55  UOS Main
2016  60  UOS Sub

The file is opened with ios::binary, and each object is written as raw bytes with write(reinterpret_cast<char*>(&b), sizeof(b)). A fixed-size char array is used for college because a std::string member stores only a pointer, which cannot be saved meaningfully in a binary file.

Q6 – Class Rational with >> and + overloaded and a zero-denominator exception

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

class Rational {
    double NUMERATOR, DENOMINATOR;
public:
    Rational() : NUMERATOR(0), DENOMINATOR(1) {}
    Rational(double n, double d) {
        if (d == 0) throw invalid_argument("Error: denominator cannot be zero!");
        NUMERATOR = n; DENOMINATOR = d;
    }
    friend istream& operator>>(istream &in, Rational &r) {
        double n, d;
        cout << "Numerator: ";   in >> n;
        cout << "Denominator: "; in >> d;
        if (d == 0) throw invalid_argument("Error: denominator cannot be zero!");
        r.NUMERATOR = n; r.DENOMINATOR = d;
        return in;
    }
    Rational operator+(const Rational &o) const {
        return Rational(NUMERATOR * o.DENOMINATOR + o.NUMERATOR * DENOMINATOR,
                        DENOMINATOR * o.DENOMINATOR);
    }
    void display() const { cout << NUMERATOR << "/" << DENOMINATOR << endl; }
};

int main() {
    try {
        Rational a, b(1, 2);
        cout << "Default object: "; a.display();
        cout << "Two-argument object: "; b.display();
        cout << "Enter first rational number" << endl;  cin >> a;
        Rational c;
        cout << "Enter second rational number" << endl; cin >> c;
        cout << "You entered: "; a.display(); c.display();
        Rational sum = a + c;
        cout << "Sum = "; sum.display();
    }
    catch (const invalid_argument &e) {
        cout << e.what() << endl;
    }
    return 0;
}

Sample runs:

Input 1 2 and 1 3:
Default object: 0/1
Two-argument object: 1/2
You entered: 1/2
1/3
Sum = 5/6

Input 1 0:
Error: denominator cannot be zero!

The default constructor sets 0/1, the two-argument constructor sets given values, operator>> (a friend function) reads numerator and denominator from cin, and operator+ returns (a·d + c·b)/(b·d). If a zero denominator is entered an invalid_argument exception is thrown and caught in main(), which prints the error message. (All programs in this answer were compiled with g++ and run.)

Q7 – (i) Features of OOP

  • Class and object – class is a blueprint, object an instance: class Student {…}; Student s1;
  • Encapsulation / data hiding – private data with public functions: private: int marks; public: void setMarks(int m);
  • Abstraction – show only essential features, hide details (abstract classes, interfaces): a Shape with area().
  • Inheritance – reuse a base class: class Car : public Vehicle.
  • Polymorphism – one interface, many forms: function/operator overloading (compile time) and virtual functions (run time).
  • Message passing and dynamic binding – objects communicate by calling methods; the function called is decided at run time.

Q7 – (ii) Function template and class template

Templates allow generic programming: one definition works for many data types; the compiler generates a version for each type used.

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

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

template <class T>
class Box {
    T value;
public:
    Box(T v) : value(v) {}
    T get() const { return value; }
};

int main() {
    cout << maximum(3, 7) << " " << maximum(2.5, 1.5) << " " << maximum('a', 'z') << endl;
    Box<int> bi(10);
    Box<string> bs("Hello");
    cout << bi.get() << " " << bs.get() << endl;
    return 0;
}

Output: 7 2.5 z and 10 Hello. maximum<T> is a function template used with int, double and char; Box<T> is a class template instantiated as Box<int> and Box<string>.

Save this paper for offline studyDownload the question paper, or save the paper together with all solved answers as a PDF.
↓ Download Paper (JPG)

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.