Browse papers
A

Section A: Long Answer Questions

Attempt any TWO questions.

3 questions·10 marks each
1long10 marks

Explain the access specifiers (public, private, protected) in C++ with examples. How do they affect inheritance?

Access Specifiers in C++

Access specifiers control the visibility/accessibility of class members (data and functions). C++ provides three specifiers:

SpecifierSame classDerived classOutside class
publicYesYesYes
protectedYesYesNo
privateYesNoNo
  • public — members are accessible from anywhere the object is visible. They form the interface of the class.
  • private — members are accessible only within the same class (and its friends). This enforces data hiding/encapsulation. By default, members of a class are private.
  • protected — like private for outside code, but accessible to derived classes. Used when subclasses need access but external code should not.

Example

class Base {
public:    int a;   // accessible everywhere
protected: int b;   // accessible in Base and derived classes
private:   int c;   // accessible only in Base
public:
    void show() { a=1; b=2; c=3; }  // all OK inside class
};

Effect on Inheritance

The mode of inheritance (public, protected, private) decides how inherited members appear in the derived class:

Base memberpublic inheritanceprotected inheritanceprivate inheritance
publicpublicprotectedprivate
protectedprotectedprotectedprivate
privatenot inheritednot inheritednot inherited
class Derived : public Base {
    void test() {
        a = 10;   // OK (public)
        b = 20;   // OK (protected)
        // c = 30; // ERROR: private to Base, not accessible
    }
};

Key points: private members are never directly accessible in a derived class (only through public/protected member functions of the base). Public inheritance models an "is-a" relationship and preserves the base interface; private inheritance hides it.

access-specifiersinheritance
2long10 marks

What is a static member? Explain static data members and static member functions with a suitable C++ program.

Static Members in C++

A static member belongs to the class itself rather than to any individual object. There is exactly one shared copy for all objects of the class, regardless of how many objects are created.

Static Data Member

  • Shared by all objects; stored once in memory.
  • Declared with static inside the class but must be defined (and initialized) outside the class.
  • Commonly used as a counter to track the number of objects.

Static Member Function

  • Can be called using the class name: ClassName::function(), even without any object.
  • Can access only static data members and other static functions (it has no this pointer).

Example Program

#include <iostream>
using namespace std;

class Counter {
    static int count;   // static data member (declaration)
public:
    Counter() { count++; }
    static int getCount() {   // static member function
        return count;
    }
};

int Counter::count = 0;   // definition + initialization outside class

int main() {
    Counter a, b, c;
    cout << "Objects created: " << Counter::getCount() << endl;
    return 0;
}

Output:

Objects created: 3

Each time an object is constructed, the single shared count is incremented, so the static function reports the total number of objects.

static-members
3long10 marks

Explain stream classes in C++. Write a program to demonstrate formatted I/O using manipulators (setw, setprecision, setfill).

Stream Classes in C++

A stream is a sequence of bytes that flows between the program and an I/O device. C++ provides a hierarchy of stream classes (defined in <iostream> and <fstream>) for device-independent I/O.

Stream Class Hierarchy

  • ios — base class; holds format state and error flags.
  • istream — input stream (derived from ios); provides >>, get(), getline().
  • ostream — output stream (derived from ios); provides <<, put(), write().
  • iostream — combines istream + ostream for bidirectional I/O.
  • ifstream / ofstream / fstream — file input/output streams (in <fstream>).

Standard objects: cin (istream), cout (ostream), cerr, clog.

Manipulators for Formatted I/O

  • setw(n) — sets the field width to n.
  • setprecision(n) — sets the number of significant/decimal digits.
  • setfill(ch) — sets the fill character used to pad the field.
  • fixed — forces fixed-point notation.

(These require #include <iomanip>.)

Program

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

int main() {
    double pi = 3.14159265;
    cout << setfill('*') << setw(10) << "PI" << endl;
    cout << fixed << setprecision(3);
    cout << setfill(' ') << setw(10) << pi << endl;
    cout << setw(8) << 42 << endl;
    return 0;
}

Sample Output:

********PI
     3.142
      42

Here setw right-justifies values in a 10/8-character field, setprecision(3) with fixed shows 3 decimal places, and setfill('*') pads the heading with asterisks.

streamsio
B

Section B: Short Answer Questions

Attempt any EIGHT questions.

9 questions·5 marks each
4short5 marks

Differentiate between class and object with examples.

Class vs Object

A class is a user-defined data type that acts as a blueprint/template — it defines the data members (attributes) and member functions (behavior) but does not occupy memory for the data. An object is an instance of a class — a concrete entity created from the blueprint that occupies memory.

ClassObject
Logical blueprint / templateReal instance of a class
Declared onceMany objects can be created from one class
No memory allocated for data membersMemory is allocated when created
Defined using class keywordCreated by declaring a variable of the class type

Example

class Car {          // class = blueprint
    string model;
public:
    void start() { cout << "Started"; }
};

int main() {
    Car c1, c2;      // c1, c2 = objects (instances)
    c1.start();
}

Here Car is the class; c1 and c2 are objects, each with its own copy of model.

class-object
5short5 marks

What is the difference between malloc/free and new/delete?

malloc/free vs new/delete

Featuremalloc / freenew / delete
OriginC library functions (<cstdlib>)C++ operators
Constructor/DestructorDoes NOT call themCalls constructor (new) and destructor (delete)
Return typevoid* — needs explicit castReturns the correct typed pointer (no cast)
SizeProgrammer must specify size in bytes (sizeof)Size computed automatically by compiler
FailureReturns NULL on failureThrows bad_alloc exception
OverloadingCannot be overloadedCan be overloaded
Reallocationrealloc() availableNo direct equivalent

Example

// C-style
int *p = (int*) malloc(5 * sizeof(int));
free(p);

// C++ style
int *q = new int[5];   // constructors run for objects
delete[] q;            // destructors run

Key point: For class objects, always use new/delete because only they invoke constructors and destructors; malloc/free only allocate/free raw memory.

memory
6short5 marks

Explain the concept of containership (composition).

Containership (Composition)

Containership, also called composition, is the mechanism in which an object of one class is created as a data member of another class — i.e., a class contains (has) an object of another class. It models a "has-a" relationship (e.g., a Car has an Engine).

This is an alternative to inheritance for code reuse: instead of being another class (is-a), the class owns another class's object and uses its functionality through that member.

Example

class Engine {
public:
    void start() { cout << "Engine started\n"; }
};

class Car {
    Engine e;          // containership: Car HAS an Engine
public:
    void drive() {
        e.start();     // use contained object
        cout << "Car is driving\n";
    }
};

Here Car contains an Engine object. The contained object's constructor runs before the container's constructor and its destructor runs after the container's. Containership promotes loose coupling and reusability.

composition
7short5 marks

What is the catch(...) handler used for?

The catch(...) Handler

The catch(...) handler is the catch-all (default) exception handler in C++. The ellipsis ... matches any type of exception, regardless of the data type thrown.

It is used when:

  • The program may throw exceptions of unknown or unanticipated types.
  • A generic fallback is needed to ensure no exception goes unhandled.

It must be placed last, after all specific catch blocks, because once reached it matches everything (a specific handler placed after it would be unreachable).

Example

try {
    throw 3.14;        // throws a double
}
catch (int e) {
    cout << "Caught int";
}
catch (...) {          // catch-all
    cout << "Caught an unknown exception";
}

Output: Caught an unknown exception

Limitation: inside catch(...) you cannot access the thrown value's details, so it is best used for cleanup or as a safety net.

exception-handling
8short5 marks

Write a short note on the friend function.

Friend Function

A friend function is a function that is not a member of a class but is granted access to the class's private and protected members. It is declared inside the class with the keyword friend, but defined outside without the scope-resolution operator and without the friend keyword.

Characteristics

  • Declared inside the class using friend.
  • Not called using an object (it is not a member); it takes the object as an argument.
  • Has no this pointer.
  • Can be a global function, or a member of another class.
  • Friendship is not inherited and is not mutual unless explicitly declared.
  • Commonly used for operator overloading (e.g. <<, >>) and when a function must access internals of two different classes.

Example

class Box {
    int width;
public:
    Box(int w) : width(w) {}
    friend void show(Box b);   // friend declaration
};

void show(Box b) {             // not a member; no Box::
    cout << "Width = " << b.width;  // accesses private member
}

Friend functions slightly break encapsulation, so they should be used only when genuinely needed.

friend-function
9short5 marks

What is a virtual base class?

Virtual Base Class

A virtual base class is used in multiple inheritance to solve the diamond problem (ambiguity) — where a class inherits the same base class more than once through different paths, creating duplicate copies of the base members.

By declaring the common base class as virtual, C++ ensures that only one shared copy of the base class sub-object is inherited, no matter how many paths lead to it.

The Diamond Problem

      A
     / \
    B   C
     \ /
      D

Without virtual, D gets two copies of A (via B and via C) → ambiguous access.

Solution

class A { public: int x; };
class B : virtual public A { };   // virtual
class C : virtual public A { };   // virtual
class D : public B, public C { };

int main() {
    D obj;
    obj.x = 5;   // OK: single shared copy of A, no ambiguity
}

With virtual, class D contains only one copy of A, so obj.x is unambiguous.

inheritance
10short5 marks

Explain the difference between ifstream and ofstream.

ifstream vs ofstream

Both are file stream classes defined in the <fstream> header.

Featureifstreamofstream
Full nameInput File StreamOutput File Stream
Derived fromistreamostream
PurposeReads data from a fileWrites data to a file
Default open modeios::inios::out (creates/truncates file)
Operators/methods>>, get(), getline()<<, put(), write()

Example

#include <fstream>
using namespace std;
int main() {
    ofstream fout("data.txt");   // open for writing
    fout << "Hello File";
    fout.close();

    ifstream fin("data.txt");    // open for reading
    string s;
    fin >> s;                    // reads "Hello"
    fin.close();
}

Summary: Use ofstream to send output to a file and ifstream to take input from a file. fstream supports both read and write.

file-handling
11short5 marks

What is an inline function and when should it be avoided?

Inline Function

An inline function is a function whose body is expanded (substituted) at the point of each call by the compiler, instead of performing a normal function call. It is declared using the inline keyword. The goal is to eliminate function-call overhead (saving/restoring registers, jumping, returning) and thus improve speed for small, frequently-called functions.

inline int square(int x) { return x * x; }

Note: inline is only a request/hint to the compiler; the compiler may ignore it.

When inline should be AVOIDED

Inlining is typically ignored or undesirable when:

  • The function is large — code is duplicated at every call site, increasing the binary size (code bloat).
  • The function contains loops, switch, goto, or recursion.
  • The function has static variables.
  • The function is called many times from many places, again causing bloat.
  • A function pointer is taken to the function.

In these cases the size/overhead trade-off is poor, so a normal (non-inline) function is preferred.

inline-function
12short5 marks

Differentiate between a member function and a friend function.

Member Function vs Friend Function

FeatureMember FunctionFriend Function
Belongs to classYes, it is a member of the classNo, it is a non-member (external) function
DeclarationDeclared and (usually) scoped with ClassName::Declared inside class with friend keyword
this pointerHas access to this pointerHas no this pointer
How calledCalled using an object: obj.func()Called like an ordinary function; object passed as argument
Access to private membersYes (it is part of the class)Yes (granted by the friend declaration)
ScopeInside the class scopeOutside the class scope

Example

class Box {
    int w;
public:
    Box(int x):w(x){}
    int getW() { return w; }            // member function
    friend int twice(Box b);            // friend declaration
};
int twice(Box b) { return 2 * b.w; }    // friend function

// Usage
Box b(5);
b.getW();    // member: called on object
twice(b);    // friend: object passed as argument

Both can access private data, but a member function operates through an object (this), while a friend function receives the object explicitly.

friend-function

Frequently asked questions

Where can I find the BSc CSIT (TU) Object-Oriented Programming (BSc CSIT, CSC161) question paper 2080?
The full BSc CSIT (TU) Object-Oriented Programming (BSc CSIT, CSC161) 2080 (regular) question paper is available free on Kekkei. You can read every question online and attempt the paper under timed exam conditions.
Does the Object-Oriented Programming (BSc CSIT, CSC161) 2080 paper come with solutions?
Yes. Every question on this Object-Oriented Programming (BSc CSIT, CSC161) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
How many marks is the BSc CSIT (TU) Object-Oriented Programming (BSc CSIT, CSC161) 2080 paper?
The BSc CSIT (TU) Object-Oriented Programming (BSc CSIT, CSC161) 2080 paper carries 60 full marks and is meant to be completed in 180 minutes, across 12 questions.
Is practising this Object-Oriented Programming (BSc CSIT, CSC161) past paper free?
Yes — reading and attempting this Object-Oriented Programming (BSc CSIT, CSC161) past paper on Kekkei is completely free.