Browse papers
A

Section A: Long Answer Questions

Attempt all / any as specified.

4 questions
1long12 marks

What is the basic difference between procedure-oriented programming and object-oriented programming? Explain the concepts of data abstraction and encapsulation with a suitable example. Write a C++ class Distance having data members feet and inches, with member functions to read data, display data, and add two distances; demonstrate its use in main().

POP vs OOP

Procedure-Oriented Programming (POP)Object-Oriented Programming (OOP)
Program is divided into functions.Program is divided into objects.
Emphasis is on doing things (procedures).Emphasis is on data.
Data moves openly between functions; mostly global.Data is hidden and bound with functions inside objects.
Follows top-down design.Follows bottom-up design.
No access control; data is unprotected.Provides access control (private, protected, public).
Examples: C, Pascal, FORTRAN.Examples: C++, Java, Python.

Data Abstraction

Abstraction means showing only the essential features of an object while hiding the unnecessary implementation details. A class is a vehicle for abstraction: the user sees what an object does (its public interface), not how it does it.

Encapsulation

Encapsulation is the wrapping of data and the functions that operate on that data into a single unit (a class), with the data kept private so it can be accessed only through public member functions (data hiding).

Example illustrating both:

class BankAccount {
private:
    double balance;          // hidden data (encapsulation)
public:
    void deposit(double amt) { balance += amt; }   // public interface (abstraction)
    double getBalance() { return balance; }
};

The user calls deposit() without knowing how balance is stored or updated — that is abstraction; the data balance and its functions are bundled and protected — that is encapsulation.

C++ Distance Class

#include <iostream>
using namespace std;

class Distance {
private:
    int feet;
    int inches;
public:
    void read() {
        cout << "Enter feet: ";   cin >> feet;
        cout << "Enter inches: "; cin >> inches;
    }
    void display() {
        cout << feet << " feet " << inches << " inches" << endl;
    }
    Distance add(Distance d) {
        Distance temp;
        temp.inches = inches + d.inches;
        temp.feet   = feet + d.feet + temp.inches / 12; // carry
        temp.inches = temp.inches % 12;
        return temp;
    }
};

int main() {
    Distance d1, d2, d3;
    cout << "First distance:\n";  d1.read();
    cout << "Second distance:\n"; d2.read();
    d3 = d1.add(d2);
    cout << "Sum = "; d3.display();
    return 0;
}

Sample output (for 5 ft 8 in + 3 ft 6 in): Sum = 9 feet 2 inches (since 8+6 = 14 in = 1 ft 2 in carried over).

classes-and-objectsconstructors
2long12 marks

(a) Define inheritance and explain its types with diagrams. What is the order of execution of constructors and destructors in multilevel inheritance? (b) What is a virtual function? Explain how runtime polymorphism is achieved in C++ using base-class pointers and virtual functions, with a program example involving a base class Shape and derived classes Circle and Rectangle.

(a) Inheritance and its Types

Inheritance is the mechanism by which one class (the derived/child class) acquires the properties (data members) and behaviours (member functions) of another class (the base/parent class). It promotes code reusability and supports the is-a relationship.

Types of inheritance:

  • Single: one derived class from one base class. A -> B
  • Multilevel: a derived class itself acts as a base for another class. A -> B -> C
  • Multiple: one derived class inherits from two or more base classes. A, B -> C
  • Hierarchical: several derived classes from a single base class. A -> B, A -> C
  • Hybrid: combination of two or more of the above types.

(Diagrams: arrows point from base class down to derived class, e.g. for multilevel a vertical chain A on top, B in the middle, C at the bottom.)

Order of execution in multilevel inheritance: Constructors are called in the order of derivation (base first, then derived)A, then B, then C. Destructors are called in reverse orderC, then B, then A.

(b) Virtual Function and Runtime Polymorphism

A virtual function is a member function declared with the keyword virtual in the base class and redefined (overridden) in derived classes. When a base-class pointer (or reference) points to a derived object and a virtual function is called through it, the function that actually runs is decided at run time based on the object's actual type — this is runtime (dynamic) polymorphism, implemented via the virtual table (vtable) and late binding.

#include <iostream>
using namespace std;

class Shape {
public:
    virtual void area() {            // virtual function
        cout << "Area of generic shape\n";
    }
    virtual ~Shape() {}
};

class Circle : public Shape {
    double r;
public:
    Circle(double radius) : r(radius) {}
    void area() override {
        cout << "Area of circle = " << 3.14159 * r * r << endl;
    }
};

class Rectangle : public Shape {
    double l, b;
public:
    Rectangle(double len, double bre) : l(len), b(bre) {}
    void area() override {
        cout << "Area of rectangle = " << l * b << endl;
    }
};

int main() {
    Shape* s;                 // base-class pointer
    Circle c(5);
    Rectangle r(4, 6);
    s = &c; s->area();        // calls Circle::area()  -> 78.5398
    s = &r; s->area();        // calls Rectangle::area() -> 24
    return 0;
}

Because area() is virtual, the correct overridden version is selected at run time according to the object the pointer refers to.

inheritancepolymorphismvirtual-functions
3long12 marks

(a) What are the rules and restrictions for operator overloading in C++? Which operators cannot be overloaded? (b) Write a class Complex to represent complex numbers. Overload the + and * operators using member functions and overload the << operator using a friend function so that complex objects can be added, multiplied, and printed directly.

(a) Rules and Restrictions for Operator Overloading

Rules:

  • Only existing operators can be overloaded; you cannot create new operator symbols.
  • At least one operand must be a user-defined type (class/struct); operators on built-in types cannot be redefined.
  • The arity (unary/binary), precedence, and associativity of an operator cannot be changed.
  • Overloading must preserve the operator's basic meaning for readability (a convention, not enforced).
  • It can be implemented as a member function or a friend/non-member function.
  • =, [], () and -> must be overloaded as member functions only.

Operators that CANNOT be overloaded:

  • . (member access)
  • .* (pointer-to-member)
  • :: (scope resolution)
  • ?: (ternary conditional)
  • sizeof
  • typeid

(b) Complex Class with Overloaded Operators

#include <iostream>
using namespace std;

class Complex {
private:
    double real, imag;
public:
    Complex(double r = 0, double i = 0) : real(r), imag(i) {}

    // member function overloading of +
    Complex operator+(const Complex& c) const {
        return Complex(real + c.real, imag + c.imag);
    }

    // member function overloading of *
    // (a+bi)(c+di) = (ac - bd) + (ad + bc)i
    Complex operator*(const Complex& c) const {
        return Complex(real * c.real - imag * c.imag,
                       real * c.imag + imag * c.real);
    }

    // friend function overloading of <<
    friend ostream& operator<<(ostream& out, const Complex& c) {
        out << c.real;
        if (c.imag >= 0) out << " + " << c.imag << "i";
        else             out << " - " << -c.imag << "i";
        return out;
    }
};

int main() {
    Complex a(2, 3), b(1, 4);
    cout << "a = " << a << "\nb = " << b << endl;
    cout << "a + b = " << (a + b) << endl;   // 3 + 7i
    cout << "a * b = " << (a * b) << endl;   // -10 + 11i
    return 0;
}

Output:

a = 2 + 3i
b = 1 + 4i
a + b = 3 + 7i
a * b = -10 + 11i

The << operator is a friend because its left operand is ostream (cout), so it cannot be a member of Complex.

operator-overloadingconstructors
4long14 marks

(a) What is a template? Differentiate between function templates and class templates with examples. Write a function template to find the maximum of two values of any data type. (b) What is the Standard Template Library (STL)? Briefly explain containers, iterators, and algorithms, and write a program using vector to store and display a list of integers in sorted order.

(a) Templates

A template is a feature of C++ that allows writing generic functions and classes that work with any data type without rewriting code for each type. The compiler generates the actual code (instantiation) when the template is used with a specific type. This supports generic programming.

Function TemplateClass Template
Generates a family of functions.Generates a family of classes.
Type deduced automatically from arguments.Type specified explicitly, e.g. Stack<int> s;.
Example: a generic max().Example: a generic Stack<T>, vector<T>.
// Function template example
template <class T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}
// Class template example
template <class T>
class Pair {
    T first, second;
public:
    Pair(T a, T b) : first(a), second(b) {}
    T getFirst() { return first; }
};

Function template to find maximum of two values:

#include <iostream>
using namespace std;

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

int main() {
    cout << maximum(10, 20) << endl;       // int  -> 20
    cout << maximum(3.5, 2.1) << endl;     // double -> 3.5
    cout << maximum('a', 'z') << endl;     // char -> z
    return 0;
}

(b) Standard Template Library (STL)

The STL is a collection of generic, template-based classes and functions in C++ providing ready-made data structures and algorithms. Its three core components are:

  • Containers: objects that store data, e.g. vector, list, deque (sequence containers); set, map (associative containers).
  • Iterators: pointer-like objects used to traverse the elements of a container (e.g. begin(), end()); they connect containers with algorithms.
  • Algorithms: generic functions that operate on ranges through iterators, e.g. sort(), find(), reverse(), count().

Program using vector to store and display integers in sorted order:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {40, 10, 30, 20, 50};
    sort(v.begin(), v.end());            // STL algorithm using iterators

    cout << "Sorted list: ";
    for (int x : v)
        cout << x << " ";                // 10 20 30 40 50
    cout << endl;
    return 0;
}

Output: Sorted list: 10 20 30 40 50

templatesstlexception-handling
B

Section B: Short Answer Questions

Attempt all / any as specified.

8 questions
5short6 marks

Differentiate between a constructor and a destructor. Explain copy constructor and parameterized constructor with a suitable code example each.

Constructor vs Destructor

ConstructorDestructor
Same name as the class.Same name as class, preceded by ~.
Called automatically when an object is created.Called automatically when an object is destroyed / goes out of scope.
Used to initialize data members and allocate resources.Used to release/clean up resources (free memory, close files).
Can be overloaded and can take parameters.Cannot be overloaded; takes no parameters and returns nothing.
There can be many constructors per class.There is only one destructor per class.

Parameterized Constructor

A constructor that accepts arguments, used to initialize an object with specific values.

class Point {
    int x, y;
public:
    Point(int a, int b) { x = a; y = b; }   // parameterized constructor
    void show() { cout << x << "," << y << endl; }
};
// usage: Point p(3, 4); p.show();  // 3,4

Copy Constructor

A constructor that creates a new object as a copy of an existing object of the same class. Its parameter is a reference to an object of the same class (const ClassName&).

class Point {
    int x, y;
public:
    Point(int a, int b) { x = a; y = b; }
    Point(const Point& p) { x = p.x; y = p.y; }   // copy constructor
    void show() { cout << x << "," << y << endl; }
};
// usage: Point p1(3, 4); Point p2(p1); p2.show();  // 3,4
constructorsdestructors
6short6 marks

Differentiate between compile-time polymorphism and run-time polymorphism. Explain function overloading with a program example.

Compile-time vs Run-time Polymorphism

Compile-time (Static) PolymorphismRun-time (Dynamic) Polymorphism
Function call is bound at compile time (early binding).Function call is bound at run time (late binding).
Achieved by function overloading and operator overloading.Achieved by virtual functions with base-class pointers/references.
Faster, no run-time overhead.Slightly slower due to vtable lookup.
No inheritance required.Requires inheritance and overriding.

Function Overloading

Function overloading means defining two or more functions with the same name but different parameter lists (different number or types of parameters). The compiler selects the correct function based on the arguments supplied.

#include <iostream>
using namespace std;

int add(int a, int b)            { return a + b; }
double add(double a, double b)   { return a + b; }
int add(int a, int b, int c)     { return a + b + c; }

int main() {
    cout << add(2, 3)        << endl;   // calls int version -> 5
    cout << add(2.5, 3.5)    << endl;   // calls double version -> 6
    cout << add(1, 2, 3)     << endl;   // calls 3-arg version -> 6
    return 0;
}

The three add functions share a name but differ in signature, so the call is resolved at compile time.

polymorphismfunction-overloading
7short6 marks

Explain the visibility of base-class members in public, private, and protected inheritance. Illustrate with a table showing how the access of members changes in the derived class.

Visibility of Base-Class Members under Different Inheritance Modes

When a class is derived, the access mode (public, protected, or private) determines how the inherited base members are accessible in the derived class. Private members of the base class are never directly accessible in the derived class regardless of the mode (they remain inaccessible).

Base member accesspublic inheritanceprotected inheritanceprivate inheritance
publicstays publicbecomes protectedbecomes private
protectedstays protectedstays protectedbecomes private
privatenot inherited (inaccessible)not inherited (inaccessible)not inherited (inaccessible)

Summary:

  • Public inheritance keeps the access levels of inherited members the same (public stays public, protected stays protected). Models the is-a relationship.
  • Protected inheritance demotes public members to protected; they are usable in further derived classes but not from outside.
  • Private inheritance makes all inherited members private to the derived class; they are not available to classes derived further.
class Base {
public:    int a;
protected: int b;
private:   int c;
};
class Derived : public Base {
    void f() { a = 1; b = 2; /* c = 3; ERROR: c is private */ }
};
inheritanceaccess-specifiers
8short6 marks

What is exception handling? Explain the use of try, catch, and throw keywords with a program that handles a division-by-zero exception.

Exception Handling

Exception handling is the mechanism in C++ to detect and respond to run-time errors (exceptions) in a structured way, allowing a program to continue or terminate gracefully instead of crashing. It separates error-handling code from normal logic.

Keywords:

  • try — encloses the block of code that might throw an exception (the guarded block).
  • throw — signals (raises) an exception when an error condition is detected, passing an exception object/value.
  • catch — immediately follows a try block and handles an exception of the matching type.

Program: Division-by-Zero Handling

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cout << "Enter two numbers: ";
    cin >> a >> b;

    try {
        if (b == 0)
            throw "Error: Division by zero!";   // throw an exception
        cout << "Result = " << a / b << endl;
    }
    catch (const char* msg) {                   // catch the exception
        cout << msg << endl;
    }
    return 0;
}

Sample run (a=10, b=0): output is Error: Division by zero! — the throw transfers control to the catch block, which displays the message and the program ends safely.

exception-handling
9short6 marks

Write a C++ program that creates a text file, writes student records (name and marks) into it, and then reads the records back from the file to display them on screen using ifstream and ofstream.

Program: Writing and Reading Student Records using File Streams

ofstream (output file stream) is used to write to a file, and ifstream (input file stream) is used to read from a file. Both are declared in the <fstream> header.

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

int main() {
    // ----- Writing records to the file -----
    ofstream fout("students.txt");
    int n;
    cout << "How many students? "; cin >> n;
    for (int i = 0; i < n; i++) {
        string name;
        int marks;
        cout << "Enter name and marks: ";
        cin >> name >> marks;
        fout << name << " " << marks << "\n";   // write to file
    }
    fout.close();

    // ----- Reading records back from the file -----
    ifstream fin("students.txt");
    string name;
    int marks;
    cout << "\nStudent Records:\n";
    cout << "Name\tMarks\n";
    while (fin >> name >> marks) {               // read until end of file
        cout << name << "\t" << marks << "\n";
    }
    fin.close();
    return 0;
}

Explanation: The program opens students.txt for output, writes each student's name and marks, and closes it. It then reopens the same file for input and reads each record back with the extraction operator >> in a loop until end-of-file, displaying the records on screen.

file-iostreams
10short6 marks

What is a pure virtual function? Explain abstract classes and their use in C++ with an example. Why can an object of an abstract class not be created?

Pure Virtual Function

A pure virtual function is a virtual function that has no definition in the base class and is declared by assigning = 0 in its declaration:

virtual void draw() = 0;   // pure virtual function

It declares an interface that every derived class must override.

Abstract Class

An abstract class is a class that contains at least one pure virtual function. It is meant to act as a base class / interface only — it provides a common structure that derived classes must implement.

Why an object of an abstract class cannot be created: Because a pure virtual function has no implementation, the class is incomplete. If an object were allowed, calling that function would have no code to execute. Therefore the compiler forbids instantiating an abstract class; we can only create pointers/references of the abstract type and objects of its concrete derived classes.

Example

#include <iostream>
using namespace std;

class Shape {              // abstract class
public:
    virtual double area() = 0;   // pure virtual function
    virtual ~Shape() {}
};

class Circle : public Shape {
    double r;
public:
    Circle(double radius) : r(radius) {}
    double area() override { return 3.14159 * r * r; }
};

int main() {
    // Shape s;            // ERROR: cannot instantiate abstract class
    Shape* p = new Circle(5);
    cout << "Area = " << p->area() << endl;   // 78.5398
    delete p;
    return 0;
}
virtual-functionsabstract-class
11short6 marks

What is a friend function? Explain its characteristics and write a program in which a friend function accesses the private members of two different classes to compute their sum.

Friend Function

A friend function is a function that is not a member of a class but is granted access to the private and protected members of that class by declaring it with the keyword friend inside the class.

Characteristics:

  • It is declared inside the class with friend but defined outside without the scope-resolution :: and without the friend keyword.
  • It is not a member, so it is not called using an object (obj.func()); it is called like an ordinary function.
  • It does not have a this pointer; it accesses members through object arguments passed to it.
  • It can be a friend of more than one class, which lets it bridge two classes.
  • Friendship is not inherited and is not mutual unless declared on both sides.

Program: Friend Function Accessing Two Classes

#include <iostream>
using namespace std;

class B;   // forward declaration

class A {
    int x;
public:
    A(int v) : x(v) {}
    friend int sum(A, B);   // friend of A
};

class B {
    int y;
public:
    B(int v) : y(v) {}
    friend int sum(A, B);   // friend of B
};

int sum(A a, B b) {          // accesses private members of both
    return a.x + b.y;
}

int main() {
    A objA(10);
    B objB(20);
    cout << "Sum = " << sum(objA, objB) << endl;   // 30
    return 0;
}

The function sum() is declared a friend in both classes A and B, so it can read their private members x and y to compute the total.

classes-and-objectsfriend-function
12short4 marks

Explain stream class hierarchy in C++. What are formatted and unformatted I/O operations? Briefly describe any three I/O manipulators with examples.

Stream Class Hierarchy in C++

A stream is a sequence of bytes flowing between a program and an I/O device. The C++ stream classes are defined in <iostream>:

  • ios — the base class; holds formatting state and error flags.
  • istream — derived from ios; supports input (>>, get, getline). cin is an istream object.
  • ostream — derived from ios; supports output (<<, put, write). cout is an ostream object.
  • iostream — derived from both istream and ostream (multiple inheritance); supports both input and output.

(File streams ifstream, ofstream, fstream are derived from these for file I/O.)

Formatted vs Unformatted I/O

  • Formatted I/O: data is converted to/from a human-readable form with formatting applied (width, precision, base). Uses <<, >> operators and manipulators. Example: cout << setw(5) << 42;.
  • Unformatted I/O: transfers raw bytes/characters without formatting. Uses functions like get(), put(), getline(), read(), write().

Three I/O Manipulators

  • endl — inserts a newline and flushes the output buffer. e.g. cout << "Hi" << endl;
  • setw(n) — sets the field width to n for the next item (needs <iomanip>). e.g. cout << setw(6) << 25;
  • setprecision(n) — sets the number of significant digits for floating-point output (with <iomanip>). e.g. cout << setprecision(3) << 3.14159; prints 3.14.
streamsmanipulators

Frequently asked questions

Where can I find the BE Computer Engineering (Pokhara University) Object Oriented Programming in C++ (PU, CMP 162) question paper 2079?
The full BE Computer Engineering (Pokhara University) Object Oriented Programming in C++ (PU, CMP 162) 2079 (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 in C++ (PU, CMP 162) 2079 paper come with solutions?
Yes. Every question on this Object Oriented Programming in C++ (PU, CMP 162) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
How many marks is the BE Computer Engineering (Pokhara University) Object Oriented Programming in C++ (PU, CMP 162) 2079 paper?
The BE Computer Engineering (Pokhara University) Object Oriented Programming in C++ (PU, CMP 162) 2079 paper carries 100 full marks and is meant to be completed in 180 minutes, across 12 questions.
Is practising this Object Oriented Programming in C++ (PU, CMP 162) past paper free?
Yes — reading and attempting this Object Oriented Programming in C++ (PU, CMP 162) past paper on Kekkei is completely free.