Blog
Object Oriented Programming Past Paper 2013 – BSCS 2nd Term UOS (CMP-240)
University of Sargodha BS Computer Science 2nd term Object-Oriented Programming (CMP-240) paper, 2013 exam (80 marks, 2:30 hours). The paper is retyped below without the handwritten marks, followed by solved answers for all 16 short questions and six tested C++ programs: a Time class, shape inheritance, a pure virtual function, polymorphism, divide-by-zero handling and a bank account file program.
Solved answers
Q1 – Short answers (16 × 2)
1. Main pillars of OOP. Encapsulation (data and functions bundled in a class, data hidden), Abstraction (showing only essential features), Inheritance (a class reuses another class) and Polymorphism (one interface, many forms).
2. Class. A user-defined type that is a blueprint for objects; it groups data members (attributes) and member functions (behaviour), e.g. class Car { string model; void start(); }; Objects are instances of the class.
3. 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.
4. 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.
5. Member functions. Functions declared inside a class that operate on its data members, e.g. void displayTime();; they are called through an object: t.displayTime();.
6. 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.
7. When is “private” used? To hide data members (and helper functions) so they can be accessed only by the class’s own member functions (and friends) – data hiding/encapsulation; outside code must use public functions.
8. 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);.
9. Virtual vs pure virtual function. A virtual function has a body in the base class and may be overridden in derived classes (virtual void show() {…}). A pure virtual function has no body (virtual void show() = 0;), makes the class abstract, and must be overridden in a derived class before objects can be created.
10. 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.
11. Destructors. A special member function ~ClassName() with no arguments and no return type, used to release resources (memory, files) held by the object. It is called automatically when the object goes out of scope or is deleted.
12. 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.
13. 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).
14. Abstraction. Showing only the essential features of an object and hiding the implementation details, e.g. using car.start() without knowing how the engine starts; achieved with classes, access specifiers and abstract classes.
15. cin.get vs cin.getline. Both read a line of characters including spaces into a char array. cin.get(name, 30) stops at the newline but leaves it in the input buffer; cin.getline(name, 30) reads and discards the newline. cin.get() with no arguments reads a single character.
16. Local variable vs data member. A local variable is declared inside a function and exists only while the function runs. A data member is declared in a class, belongs to each object and lives as long as the object; it is accessible to all member functions.
Q2 – Class Time
#include <iostream>
using namespace std;
class Time {
int hours, minutes, seconds;
public:
Time() : hours(0), minutes(0), seconds(0) {} // default constructor
Time(int h, int m, int s) : hours(h), minutes(m), seconds(s) {} // overloaded constructor
void setHours(int h) { hours = h; }
void setMinutes(int m) { minutes = m; }
void setSeconds(int s) { seconds = s; }
int getHours() const { return hours; }
int getMinutes() const { return minutes; }
int getSeconds() const { return seconds; }
void displayTime() const {
cout << "Time is " << hours << " hours : " << minutes
<< " minutes : " << seconds << "seconds" << endl;
}
};
int main() {
Time t1(12, 30, 10);
t1.displayTime();
Time t2;
t2.setHours(9); t2.setMinutes(5); t2.setSeconds(45);
t2.displayTime();
return 0;
}Output:
Time is 12 hours : 30 minutes : 10seconds
Time is 9 hours : 5 minutes : 45secondsQ3 – shape, circle, square, triangle
#include <iostream>
using namespace std;
class shape {
public:
virtual void draw() { cout << "This is a shape" << endl; }
virtual ~shape() {}
};
class circle : public shape {
public:
void draw() { cout << "This is a circle" << endl; }
};
class square : public shape {
public:
void draw() { cout << "This is a square" << endl; }
};
class triangle : public shape {
public:
void draw() { cout << "This is a triangle" << endl; }
};
int main() {
circle c; square s; triangle t;
c.draw(); s.draw(); t.draw();
shape* p[3] = { &c, &s, &t }; // same call through base pointers
for (int i = 0; i < 3; i++) p[i]->draw();
return 0;
}Output: “This is a circle”, “This is a square”, “This is a triangle” (printed twice – once through each object, once through base-class pointers, showing run-time polymorphism with virtual draw()).
Q4 – Class with a pure virtual function
A class with a pure virtual function is abstract and cannot be instantiated directly (Shape s; is a compile error). We derive a concrete class that overrides the function and create objects of the derived class; a base-class pointer or reference can then refer to them.
#include <iostream>
using namespace std;
class Shape { // abstract class
public:
virtual double area() = 0; // pure virtual function
virtual ~Shape() {}
};
class Rectangle : public Shape {
double l, w;
public:
Rectangle(double a, double b) : l(a), w(b) {}
double area() { return l * w; } // overrides the pure virtual function
};
int main() {
// Shape s; // error: cannot instantiate an abstract class
Rectangle r(4, 5); // object of the derived (concrete) class
Shape* p = &r; // base pointer/reference is allowed
cout << "Area = " << p->area() << endl;
return 0;
}Output: Area = 20
Q5 – Program to explain polymorphism
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() { cout << "Animal makes a sound" << endl; }
virtual ~Animal() {}
};
class Dog : public Animal {
public:
void sound() { cout << "Dog barks" << endl; }
};
class Cat : public Animal {
public:
void sound() { cout << "Cat meows" << endl; }
};
// compile-time polymorphism: function overloading
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int main() {
cout << add(2, 3) << " " << add(2.5, 1.5) << endl;
Animal* a[3] = { new Animal, new Dog, new Cat };
for (int i = 0; i < 3; i++) {
a[i]->sound(); // run-time polymorphism
delete a[i];
}
return 0;
}Output:
5 4
Animal makes a sound
Dog barks
Cat meowsadd() shows compile-time polymorphism (overloading); sound() called through Animal* shows run-time polymorphism – the function of the actual object runs because sound() is virtual.
Q6 – Divide 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. Integer division by zero is not a C++ exception by itself, so we check the divisor and throw.
Q7 – Bank accounts in credit.dat
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Account {
int number;
string name;
double balance;
};
const int MAX = 100;
int load(Account a[]) { // read all records from credit.dat
ifstream in("credit.dat");
int n = 0;
while (n < MAX && in >> a[n].number >> a[n].name >> a[n].balance) n++;
return n;
}
void save(Account a[], int n) { // write all records back
ofstream out("credit.dat");
for (int i = 0; i < n; i++)
out << a[i].number << " " << a[i].name << " " << a[i].balance << "\n";
}
void show(Account a[], int n) {
for (int i = 0; i < n; i++)
cout << a[i].number << "\t" << a[i].name << "\t" << a[i].balance << "\n";
}
int main() {
Account acc[MAX];
int n = load(acc), choice;
do {
cout << "\n1. Add account 2. Delete account 3. Show all 0. Exit\nChoice: ";
if (!(cin >> choice)) break;
if (choice == 1 && n < MAX) {
cout << "Account no, name, balance: ";
cin >> acc[n].number >> acc[n].name >> acc[n].balance;
n++;
save(acc, n);
} else if (choice == 2) {
int no, i;
cout << "Account no to delete: ";
cin >> no;
for (i = 0; i < n && acc[i].number != no; i++) ;
if (i == n) cout << "Account not found\n";
else {
for (int j = i; j < n - 1; j++) acc[j] = acc[j + 1];
n--;
save(acc, n);
cout << "Account deleted\n";
}
} else if (choice == 3) show(acc, n);
} while (choice != 0);
return 0;
}Test: credit.dat contained “101 Ali 5000” and “102 Sara 7000”; adding 103 Usman 2500 and deleting 101 left the file with 102 Sara 7000 and 103 Usman 2500. (Names are single words because they are read with >>.)
All programs were compiled with g++ and run; the outputs shown are from those runs.
