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

Object Oriented Programming Past Paper 2013 – BS IT 2nd Term UOS (CMP-240)

ProgramBS IT
Term2nd
Year2013
Course codeCMP-240
AnswersSolved ✓

University of Sargodha BS IT 2nd term Object-Oriented Programming (CMP-240) paper, 2013 exam (60 marks, 2:30 hours). The paper is retyped below without the handwritten roll number, followed by solved answers for all 12 short questions (with a UML class and object diagram) and all subjective questions: a clock class, an is-a inheritance program with UML, method overriding, static vs dynamic binding and exception handling. Every program was compiled and run.

Solved answers

Q1 – Short answers (12 × 2)

1. Two main programming methodologies. Procedural (structured) programming divides a program into functions that work on separate data (C, Pascal). Object-oriented programming models the problem as objects that combine data and functions, using encapsulation, inheritance and polymorphism (C++, Java).

2. Inheritance and its use. Inheritance lets a new (derived) class acquire the data members and member functions of an existing (base) class, e.g. class Student : public Person. It is useful for code reuse, extending existing code without changing it, building class hierarchies and enabling polymorphism.

3. Multiple vs multi-level inheritance. Multiple inheritance: one class derives from two or more base classes (class C : public A, public B). Multi-level inheritance: a chain, where a derived class becomes the base of another (A → B → C).

4. Access specifiers. Keywords that control access to class members: public (accessible everywhere), private (only inside the class and friends), protected (inside the class and its derived classes).

5. Constructors and properties. A constructor is a special member function that initialises an object automatically when it is created. Properties: same name as the class; no return type (not even void); called automatically; can be overloaded; can have default arguments; cannot be virtual; if none is written the compiler provides a default one.

6. Parameterized vs parameter-less constructors. A parameter-less (default) constructor takes no arguments and gives default values: Time() { h = m = s = 0; } – used by Time t;. A parameterized constructor takes arguments to set initial values: Time(int a, int b, int c) { h = a; m = b; s = c; } – used by Time t(12, 30, 10);.

7. Encapsulation. Wrapping data and the functions that operate on it into a single unit (class) and hiding the data with private access, so it is changed only through public member functions.

8. Exceptions. Exceptions are run-time errors or unusual conditions that disrupt normal program flow and are handled with try/catch. Examples: division by zero, out_of_range (array/vector index), bad_alloc (memory allocation failure), invalid_argument, file not found.

9. Abstract classes. A class that has at least one pure virtual function (virtual void draw() = 0;). It cannot be instantiated; it serves as a base class that defines an interface which derived classes must implement.

10. Polymorphism. The ability of the same function call to behave differently for different objects: compile-time (function/operator overloading, templates) and run-time (virtual functions, overriding, called through base pointers).

11. UML class and object. A class is drawn as a rectangle with three compartments: name, attributes (− private, + public) and operations. An object is a rectangle with the underlined name “objectName : ClassName” and attribute values.

+-------------------+        +------------------------+
|      Student      |        |   s1 : Student         |
+-------------------+        +------------------------+
| - rollNo : int    |        | rollNo = 15            |
| - name : string   |        | name = "Ali"           |
+-------------------+        +------------------------+
| + display() : void|
+-------------------+

12. Class vs structure. In C++ the only language difference is default access: members of a class are private by default, members of a struct are public by default (also default inheritance). By convention structs hold plain data and classes hold data plus behaviour.

Q2 – clock class with incrementSeconds()

The class is called Clock because a class named clock clashes with the standard library function clock() (compiling with “clock” gives errors).

#include <iostream>
using namespace std;

// named Clock (capital C): "clock" clashes with the standard clock() function
class Clock {
    int hour, minute, second;
public:
    Clock(int h = 0, int m = 0, int s = 0) : hour(h), minute(m), second(s) {}
    void incrementSeconds() {
        second++;
        if (second == 60) { second = 0; minute++; }
        if (minute == 60) { minute = 0; hour++; }
        if (hour == 24)   { hour = 0; }
    }
    void displayTime() const {
        cout << "Time is " << hour << " hours : " << minute
             << " minutes : " << second << "seconds" << endl;
    }
};

int main() {
    Clock c(12, 30, 9);
    c.incrementSeconds();
    c.displayTime();            // Time is 12 hours : 30 minutes : 10seconds
    Clock d(23, 59, 59);
    d.incrementSeconds();
    d.displayTime();            // Time is 0 hours : 0 minutes : 0seconds
    return 0;
}

Output:

Time is 12 hours : 30 minutes : 10seconds
Time is 0 hours : 0 minutes : 0seconds

Q3 – Inheritance and the “Is-a” relationship

Inheritance creates a new class from an existing one. Public inheritance models an “is-a” relationship: a Student is a Person, so a Student object has everything a Person has plus its own members.

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

class Person {                         // base class
protected:
    string name;
    int age;
public:
    Person(string n, int a) : name(n), age(a) {}
    void showPerson() { cout << "Name: " << name << ", Age: " << age << endl; }
};

class Student : public Person {        // Student IS-A Person
    int rollNo;
public:
    Student(string n, int a, int r) : Person(n, a), rollNo(r) {}
    void showStudent() {
        showPerson();                  // inherited member function
        cout << "Roll No: " << rollNo << endl;
    }
};

int main() {
    Student s("Ali", 20, 15);
    s.showStudent();
    return 0;
}

Output: Name: Ali, Age: 20 / Roll No: 15

UML diagram (hollow triangle arrow from derived to base):

+--------------------+
|       Person       |
+--------------------+
| # name : string    |
| # age : int        |
+--------------------+
| + showPerson()     |
+--------------------+
          ^
          |   (is-a)
+--------------------+
|      Student       |
+--------------------+
| - rollNo : int     |
+--------------------+
| + showStudent()    |
+--------------------+

Q4 – Method overriding

Method overriding is redefining a base-class member function in a derived class with the same name, return type and parameters, so the derived version runs for derived objects. In C++ the base function should be virtual so the overriding version is chosen at run time even through a base pointer/reference.

#include <iostream>
using namespace std;

class Base {
public:
    virtual void show() { cout << "Base class show()" << endl; }
    virtual ~Base() {}
};
class Derived : public Base {
public:
    void show() { cout << "Derived class show()" << endl; }   // overrides Base::show
};

int main() {
    Base b; Derived d;
    b.show();
    d.show();
    Base* p = &d;
    p->show();               // calls Derived::show because show() is virtual
    return 0;
}

Output:

Base class show()
Derived class show()
Derived class show()

Q5 – Static and dynamic binding

Static (early) bindingDynamic (late) binding
When decidedAt compile timeAt run time
Based onType of the pointer/reference/variableType of the actual object pointed to
MechanismNormal function calls, overloading, templatesVirtual functions and the vtable (vptr)
SpeedFasterSlight overhead
Exampleadd(2, 3) vs add(2.5, 1.5)Base* p = &d; p->show(); calls Derived::show()

Role in polymorphism: static binding gives compile-time polymorphism (function and operator overloading); dynamic binding gives run-time polymorphism – one interface (a base-class pointer) can call different implementations depending on the object, which makes programs extensible (new derived classes work with old code).

Q6 – Exception handling mechanism

When an error occurs, the code throws an exception object; control jumps out of the normal flow to a matching catch block; the code that may fail is placed in a try block. If no handler matches, std::terminate() ends the program.

  • try – encloses statements that may throw an exception.
  • throw – raises an exception: throw runtime_error("message"); or throw 0;.
  • catch – handles an exception of a given type; several catch blocks can follow one try; catch (...) catches everything.
try {
    // statements that may throw
    if (error) throw exceptionObject;
}
catch (Type1 e) {
    // handle Type1
}
catch (...) {
    // handle any other exception
}

Q7 – Division by zero exception

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

double divide(double a, double b) {
    if (b == 0)
        throw runtime_error("Error: division by zero");
    return a / b;
}

int main() {
    double x, y;
    cout << "Enter two numbers: ";
    cin >> x >> y;
    try {
        double r = divide(x, y);        // may throw
        cout << "Result = " << r << endl;
    }
    catch (const runtime_error& e) {
        cout << e.what() << endl;
    }
    return 0;
}

Runs: “10 0” → Error: division by zero; “10 4” → Result = 2.5.

All programs were compiled with g++ and run; the outputs shown are from those runs.

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.