Welcome to Edugrown – Your Learning Partner EduGrown
🕑 Aaj 2 free content aur bacha hai. Login karein →
← Back to UG & PG Content
Exam Papers

B.Tech 2nd Year Object Oriented Programming & Methodology CS-305 Previous Year Question Paper Solution - June 2023

RGPV University (RGPV) · MP · Engineering (B.Tech / B.E.) · Computer science · 2nd Year · Semester 3 · 16 views

Advertisement
CS/CT/CO-305 (GS) · RGPV Bhopal
Object Oriented Programming & Methodology
B.Tech., III Semester · Examination, June 2023 · Grading System (GS)
Time: Three hours · Maximum marks: 70 · Attempt any five questions; all questions carry equal marks.
This paper at a glance
Q1
a OOP vs Procedural Programming ★
b What is OOP? Features of OOP ★
Q2
a Encapsulation & data abstraction ★
b Message passing ★
Q3
a Association & its types ★
b Inheritance & its types ★
Q4
a Polymorphism & its types ★
b Program: area by overloading
Q5
a Multithreading ★
b Library management system ★
Q6
a Exception handling ★
b Methods of passing arguments
Q7
a Program: Emp.dat net salary
b File handling & stream functions ★
Q8
a Ambiguity in multiple inheritance ★
b Object model & elements (ATM) ★
c Access modifiers ★
14 of 17 parts (★) were also asked in other years. Marks by unit (out of 112 offered):
U1 39.7
U2 18.7
U3 18.7
U4 14
U5 21
Unit 1: Introduction to OOPUnit 2: Classes, Encapsulation & AbstractionUnit 3: Inheritance & RelationshipsUnit 4: PolymorphismUnit 5: Strings, Exceptions, Threads & Collections

Question 1 14 marks

(a)
Compare the object-oriented programming language with procedure programming language.
Unit 1: Introduction to OOP7 marksAlso asked in Dec 2023, Dec 2024, Dec 2025
ANSWER

Procedure-Oriented Programming (POP)

In procedure-oriented programming, a program is viewed as a sequence of tasks. The problem is divided into functions (procedures), and the main focus is on what steps must be performed. Most of the data is kept global and is shared by all functions, so data moves openly from one function to another. Program design follows the top-down approach. Examples: C, Pascal, FORTRAN, COBOL.

Object-Oriented Programming (OOP)

In object-oriented programming, a program is divided into objects. Each object combines data (attributes) and the functions (methods) that work on that data into one unit. Data is hidden from outside functions and can be accessed only through the object's own methods. Program design follows the bottom-up approach. Examples: C++, Java, C#, Python.

Procedure-Oriented ProgrammingObject-Oriented ProgrammingGlobal DataFunction 1local dataFunction 2local dataFunction 3local dataData is global and moves freelybetween all functions.Object ADataFunctionsObject BDataFunctionsObject CDataFunctionsmessagemessagemessageData is hidden inside objects; objects talk by messages.
Structure of a procedural program (left) and an object-oriented program (right)

Differences between POP and OOP

Basis Procedure-Oriented Programming Object-Oriented Programming
Basic unit Program is divided into functions. Program is divided into objects.
Focus Importance is given to functions (algorithms). Importance is given to data.
Design approach Top-down approach. Bottom-up approach.
Data security Data is global and can be changed by any function; less secure. Data is hidden inside objects (data hiding); more secure.
Access specifiers No access specifiers. Has private, protected and public.
Data movement Data moves freely from function to function. Objects communicate through member functions (message passing).
Adding new data / functions Difficult; a change in global data affects many functions. Easy; new data and functions can be added to a class without disturbing others.
Reusability Limited reusability. High reusability through inheritance.
Polymorphism / overloading Not supported. Function and operator overloading, virtual functions are supported.
Real-world modelling Poor; does not map naturally to real-world entities. Good; objects model real-world entities.
Suitable for Small and simple programs. Large and complex software.
Examples C, Pascal, FORTRAN, COBOL. C++, Java, C#, Python.

Small example

// POP style (C): data and functions are separate
struct Student { int roll; float marks; };
void display(struct Student s) { printf("%d %f", s.roll, s.marks); }

// OOP style (C++): data and functions are bound together
class Student {
    int roll; float marks;             // hidden data
public:
    void display() { cout << roll << " " << marks; }
};

Conclusion: POP concentrates on procedures, whereas OOP concentrates on data and the objects that own it. Because of data hiding, inheritance and polymorphism, OOP is preferred for large, real-world software.

(b)
Explain features of object-oriented programming with giving suitable examples.
Unit 1: Introduction to OOP7 marksAlso asked in Nov 2022, Dec 2023, Dec 2024, Dec 2025
ANSWER

Object Oriented Programming

Object Oriented Programming (OOP) is a programming approach in which a program is organised around objects rather than functions. An object is a unit that contains data and the functions that operate on that data. OOP provides a way of modularising a program by creating separate memory areas for data and functions, which can be used as templates (classes) to create as many copies (objects) as needed.

Characteristics of OOP: emphasis is on data rather than procedure; programs are divided into objects; data is hidden and cannot be accessed by external functions; objects communicate with each other through functions; new data and functions can be easily added; follows the bottom-up approach.

ClassObjectEncapsulationData AbstractionInheritancePolymorphismDynamic BindingMessage PassingOOP
Basic concepts (features) of object-oriented programming

Features of the Object-Oriented Paradigm

1. Class - A class is a user-defined data type that acts as a blueprint for objects. It defines the data members and member functions that its objects will have. Example: class Car { string model; void drive(); };

2. Object - An object is an instance of a class; it is a run-time entity that occupies memory. Every object has state, behaviour and identity. Example: Car c1, c2; creates two objects of class Car.

3. Encapsulation - Wrapping up of data and functions into a single unit (class) is called encapsulation. The data is not accessible to the outside world; only the class functions can access it. This insulation of data is called data hiding. Example: balance is private in class Account and is changed only through deposit() and withdraw().

4. Data Abstraction - Abstraction means representing the essential features without including the background details. A class gives an abstract view: the user knows what an object does, not how it does it. Example: a driver uses the steering and brake without knowing the internal engine mechanism.

5. Inheritance - Inheritance is the process by which objects of one class acquire the properties of another class. It supports reusability and represents an "is-a" relationship. Example: class Car : public Vehicle { }; - a Car is a Vehicle.

6. Polymorphism - Polymorphism means "one name, many forms". The same function or operator behaves differently in different situations. Example: + adds two numbers but joins two strings; area() computes the area of a circle or a rectangle depending on the object.

7. Dynamic Binding - Binding means linking a function call with the code to be executed. In dynamic (late) binding, the code to be executed is decided at run time. It is achieved in C++ through virtual functions.

8. Message Passing - Objects communicate with one another by sending and receiving messages. A message is a request to an object to execute one of its methods. Example: account.withdraw(500); - here account is the receiver, withdraw is the message and 500 is the information passed.

class Shape {                          // class (encapsulation + abstraction)
protected: float dim;                  // hidden data
public:
    virtual float area() = 0;          // polymorphism via dynamic binding
};
class Circle : public Shape {          // inheritance
public:
    float area() { return 3.14 * dim * dim; }
};
Circle c;  c.area();                   // object + message passing

Question 2 14 marks

(a)
Explain the concept of Encapsulation and data abstraction in detail. Write a C++ program to show these concepts in object-oriented programming methodology. Define scope and life of any variable.
Unit 2: Classes, Encapsulation & Abstraction7 marksAlso asked in Dec 2023, Dec 2024, Dec 2025
ANSWER

Encapsulation

Encapsulation is the wrapping up of data and the functions that operate on that data into a single unit called a class. The data is kept private, so it cannot be accessed directly from outside; it can be used only through the public member functions of the class. This protection of data is called data hiding or information hiding. Example: A capsule wraps different medicines inside one cover; similarly a class wraps data and functions.

Data abstraction

Data abstraction is the process of representing only the essential features of an object and hiding the background details (implementation). The user knows what an object does through its public interface but not how it does it. Example: We switch on a TV with a remote without knowing the internal circuit. In C++, abstraction is achieved by classes with public member functions, by header files, and by abstract classes. Classes that use this concept are called Abstract Data Types (ADT).

Basis Encapsulation Data Abstraction
Meaning Binding data and functions together and hiding data. Showing only essential details, hiding implementation.
Level Implementation level - how data is protected. Design level - what is shown to the user.
Achieved by Class + access specifiers (private, public). Public interface, abstract classes, header files.
Focus Data protection (data hiding). Reducing complexity.
Example balance is private in BankAccount. User calls withdraw() without knowing its checks.

How these concepts enhance software development

  1. Security and integrity - data cannot be changed accidentally; every change passes through validated methods.
  2. Reduced complexity - programmers use objects through simple interfaces without knowing internal details.
  3. Easy maintenance - the internal code of a class can be changed without affecting the code that uses it.
  4. Modularity and team work - each class is an independent module that can be developed and tested separately.
  5. Reusability - well-encapsulated classes can be reused in other programs.
  6. Loose coupling - modules depend on interfaces, not on implementations, so the system is flexible.

Program demonstrating encapsulation and abstraction

C++ Program (compiled and tested)
#include <iostream>
#include <string>
using namespace std;

class BankAccount {
private:                              // data is hidden (encapsulation)
    string holder;
    double balance;
    bool isValid(double amt) {        // internal detail (abstraction)
        return amt > 0;
    }
public:                               // simple interface for the user
    BankAccount(string h, double b) {
        holder = h;
        balance = b;
    }
    void deposit(double amt) {
        if (isValid(amt)) balance += amt;
    }
    void withdraw(double amt) {
        if (isValid(amt) && amt <= balance) balance -= amt;
        else cout << "Withdrawal of " << amt << " refused" << endl;
    }
    double getBalance() { return balance; }
};

int main() {
    BankAccount acc("Rahul", 5000);
    acc.deposit(2000);
    acc.withdraw(10000);
    acc.withdraw(1500);
    // acc.balance = 1000000;         // ERROR: balance is private
    cout << "Current balance = " << acc.getBalance() << endl;
    return 0;
}
OUTPUT
Withdrawal of 10000 refused
Current balance = 5500

Here holder and balance are encapsulated (private). The user works only with deposit(), withdraw() and getBalance(); the validation done by the private function isValid() is abstracted (hidden).

Scope and lifetime of a variable

  • Scope is the region of the program in which a variable is visible and can be used.
  • Lifetime is the duration for which the variable exists in memory during execution.
Variable Scope Lifetime
Local (automatic) Block / function in which it is declared Created when the block is entered, destroyed when it ends
Static local Block in which it is declared Whole program; keeps its value between calls
Global Entire file (from point of declaration) Whole program
Dynamic (new) Through the pointer that holds it From new until delete
Data member Class scope (accessed through the object) Same as the lifetime of its object
C++ Program (compiled and tested)
#include <iostream>
using namespace std;

int counter = 0;                 // global: file scope, lives whole program

void visit() {
    static int calls = 0;        // static local: block scope, lives whole program
    int temp = 5;                // automatic local: created on every call
    calls++;
    counter++;
    temp++;
    cout << "calls = " << calls << ", temp = " << temp << endl;
}                                // temp is destroyed here

int main() {
    visit();
    visit();
    visit();
    {
        int inner = 10;          // scope: only inside this block
        cout << "inner = " << inner << endl;
    }                            // lifetime of inner ends here
    // cout << inner;            // ERROR: inner is out of scope
    cout << "counter = " << counter << endl;
    return 0;
}
OUTPUT
calls = 1, temp = 6
calls = 2, temp = 6
calls = 3, temp = 6
inner = 10
counter = 3
(b)
What is Message Passing? How it can be achieved in C++ Programming language?
Unit 2: Classes, Encapsulation & Abstraction7 marksAlso asked in Dec 2024
ANSWER

Message passing

In OOP, objects communicate with one another by sending and receiving messages. A message is a request to an object to invoke one of its methods. The object that sends the request is the sender and the object that receives it is the receiver. The receiver responds by executing the method and may return a result.

A message has three parts: (1) the receiver object, (2) the name of the method to be invoked and (3) the information (arguments) needed by the method.

account . withdraw ( 500 );
//  receiver   method     argument
c : Customername = "Ravi"acc : Accountbalance = 3000message: acc.withdraw(1200)reply: trueSENDERRECEIVERreceiver object . method name ( arguments )
Message passing between a sender object and a receiver object

Steps in message passing

  1. Create classes that define objects and their behaviour.
  2. Create objects from the classes.
  3. Establish communication: the sender object calls a method of the receiver object.
  4. The receiver executes the method and returns the response.

How message passing facilitates communication between objects

  • Data stays hidden: the sender never touches the receiver's data directly; it only asks the receiver to act, which preserves encapsulation.
  • Loose coupling: the sender needs to know only the method name and arguments, not the internal implementation.
  • Natural modelling: it mirrors real life - a customer asks the bank to withdraw money.
  • Supports polymorphism: the same message (e.g. draw()) can be sent to different objects, and each responds in its own way.
  • Modularity: objects can be developed and replaced independently as long as they understand the same messages.

Achieving message passing in C++

In C++, message passing is done by calling member functions of objects using the dot operator (obj.method(args)) or the arrow operator with pointers (ptr->method(args)). Arguments carry the information and the return value carries the reply.

C++ Program (compiled and tested)
#include <iostream>
#include <string>
using namespace std;

class Account {                              // receiver object
    double balance;
public:
    Account(double b) { balance = b; }
    bool withdraw(double amt) {              // method invoked by the message
        if (amt <= balance) {
            balance -= amt;
            return true;
        }
        return false;
    }
    double getBalance() { return balance; }
};

class Customer {                             // sender object
    string name;
public:
    Customer(string n) { name = n; }
    void buy(Account &acc, double price) {
        if (acc.withdraw(price))             // message: receiver.method(argument)
            cout << name << " paid " << price << ", balance left: "
                 << acc.getBalance() << endl;
        else
            cout << name << ": insufficient balance for " << price << endl;
    }
};

int main() {
    Account acc(3000);
    Customer c("Ravi");
    c.buy(acc, 1200);
    c.buy(acc, 2500);
    return 0;
}
OUTPUT
Ravi paid 1200, balance left: 1800
Ravi: insufficient balance for 2500

Here the Customer object sends the message withdraw(price) to the Account object; the account decides whether the request is allowed and replies with true or false.

Question 3 14 marks

(a)
What is Association? Explain different types of association with example.
Unit 3: Inheritance & Relationships7 marksAlso asked in Nov 2022, Dec 2023
ANSWER

Association

Association is a relationship between two (or more) classes in which the objects of one class are connected with and use the objects of another class. Both objects have their own independent lifetime; neither owns the other. It is described as a "uses-a" or "knows-a" relationship. Examples: Doctor - Patient, Teacher - Student, Customer - Bank, Driver - Car. In C++, association is implemented by keeping a pointer or reference to the other object, or by passing the object to a member function.

Types of association

(a) Based on multiplicity (number of objects involved)

Type Meaning Example
One-to-one (1 : 1) One object is linked with exactly one object. Person - Passport
One-to-many (1 : *) One object is linked with many objects. Teacher - Students
Many-to-one (* : 1) Many objects are linked with one object. Students - College
Many-to-many ( : ) Many objects are linked with many objects. Students - Courses

(b) Based on direction

  • Unidirectional association - only one class knows the other (a Customer knows its Order, but Order does not keep the customer).
  • Bidirectional association - both classes know each other (a Doctor has a list of patients and each Patient knows the doctor).

(c) Reflexive (self / unary) association - a class is associated with itself. Example: an Employee is the manager of other employees.

(d) Special forms of association

  • Aggregation (weak "has-a"): the part can exist without the whole - Department and Teacher.
  • Composition (strong "part-of"): the part cannot exist without the whole - House and Room.
One-to-onePersonPassportowns11One-to-manyTeacherStudentteaches1*Many-to-oneStudentCollegestudies in*1Many-to-manyStudentCourseenrols in**Employeemanages0..1*Reflexive (self)association
Association with multiplicity, and its special forms

Program: association

C++ Program (compiled and tested)
#include <iostream>
#include <string>
using namespace std;

class Patient {
    string name;
public:
    Patient(string n) { name = n; }
    string getName() { return name; }
};

class Doctor {
    string name;
public:
    Doctor(string n) { name = n; }
    void treat(Patient &p) {              // association: Doctor uses a Patient
        cout << "Dr. " << name << " is treating " << p.getName() << endl;
    }
};

int main() {
    Doctor d("Mehta");
    Patient p1("Arjun"), p2("Sara");      // objects live independently
    d.treat(p1);
    d.treat(p2);
    return 0;
}
OUTPUT
Dr. Mehta is treating Arjun
Dr. Mehta is treating Sara

The Doctor object uses Patient objects through a reference, but neither creates nor destroys the other - this is a pure association.

(b)
Describe the role of Inheritance in object-oriented programming. Give different types of inheritance.
Unit 3: Inheritance & Relationships7 marksAlso asked in Dec 2024, Dec 2025
ANSWER

Inheritance

Inheritance is the mechanism by which a new class acquires the data members and member functions of an existing class. The existing class is called the base class (parent / super class) and the new class is called the derived class (child / sub class). The derived class can use the inherited members, add its own members and redefine (override) inherited functions. Inheritance represents an "is-a" relationship - a Car is a Vehicle.

Syntax:

class DerivedClass : visibility-mode BaseClass {
    // new members of the derived class
};
class Car : public Vehicle { ... };     // visibility mode: public / protected / private

Role (purpose) of inheritance

  1. Code reusability - code written once in the base class is reused by all derived classes.
  2. Extensibility - new features are added in derived classes without changing tested base code.
  3. Hierarchical classification - real-world "is-a" hierarchies are represented naturally (Animal → Mammal → Dog).
  4. Supports polymorphism - a base-class pointer can refer to derived objects and call overridden functions.
  5. Less redundancy and easier maintenance - common code is kept in one place, so a correction is made only once.
  6. Saves time and cost of development and testing.

Types of inheritance

SingleMultipleMultilevelHierarchicalHybridABABCABCABCDABCD
Types of inheritance (arrow points from derived class to base class)

1. Single inheritance - one derived class inherits from one base class.

class B : public A { };                       // Car : Vehicle

2. Multiple inheritance - one derived class inherits from two or more base classes.

class C : public A, public B { };             // Smartphone : Phone, Camera

3. Multilevel inheritance - a class is derived from another derived class (a chain).

class B : public A { };  class C : public B { };    // Vehicle → Car → ElectricCar

4. Hierarchical inheritance - many derived classes inherit from one base class.

class B : public A { };  class C : public A { };    // Shape → Circle, Square

5. Hybrid inheritance - a combination of two or more types (for example hierarchical + multiple). It may lead to the diamond problem, which is solved with virtual base classes (see the answer on ambiguity in multiple inheritance).

Program: single and multilevel inheritance

C++ Program (compiled and tested)
#include <iostream>
using namespace std;

class Vehicle {                            // base class
protected:
    int wheels;
public:
    void setWheels(int w) { wheels = w; }
    void showWheels() { cout << "Wheels: " << wheels << endl; }
};

class Car : public Vehicle {               // single inheritance: Car IS-A Vehicle
public:
    void drive() { cout << "Car is driving" << endl; }
};

class ElectricCar : public Car {           // multilevel inheritance
public:
    void charge() { cout << "Electric car is charging" << endl; }
};

int main() {
    ElectricCar e;
    e.setWheels(4);       // inherited from Vehicle
    e.showWheels();       // inherited from Vehicle
    e.drive();            // inherited from Car
    e.charge();           // its own function
    return 0;
}
OUTPUT
Wheels: 4
Car is driving
Electric car is charging

ElectricCar uses setWheels() and showWheels() of Vehicle and drive() of Car without rewriting them - this is reusability through inheritance.

Question 4 14 marks

(a)
Discuss Polymorphism in detail. What are the different ways to implement Polymorphism in C++, discuss them in brief. Give differences between function overloading and function overriding (or method overriding) by writing its syntax.
Unit 4: Polymorphism7 marksAlso asked in Nov 2022, Dec 2023, Dec 2024, Dec 2025
ANSWER

Polymorphism

The word polymorphism comes from Greek: poly = many, morph = forms. In OOP, polymorphism is the ability of one name (function or operator) to take many forms, i.e. the same message produces different behaviour depending on the type of data or object. Real-life example: a person behaves as a student in college, a customer in a shop and a son at home - one person, many roles. Programming example: + adds two integers but joins two strings.

PolymorphismCompile-timestatic / early bindingRun-timedynamic / late bindingFunctionoverloadingOperatoroverloadingTemplates(generic)Virtual functions(function overriding)
Types of polymorphism in C++

Types of polymorphism

1. Compile-time (static) polymorphism - the function to be called is decided by the compiler from the number and types of arguments (early / static binding). It is implemented by:

  • Function overloading - many functions with the same name but different parameter lists.
  • Operator overloading - giving an extra meaning to an existing operator for user-defined types.
  • Templates - generic functions / classes that work with any data type.

2. Run-time (dynamic) polymorphism - the function to be called is decided at run time according to the actual object pointed to (late / dynamic binding). It is implemented by:

  • Function overriding with virtual functions - a derived class redefines a virtual function of its base class, and the call is made through a base-class pointer or reference.

Ways to implement polymorphism in C++ (in brief)

int  add(int a, int b);                 // 1. function overloading
double add(double a, double b);

Complex operator+(Complex c);           // 2. operator overloading

template <class T> T maxOf(T a, T b);   // 3. templates (generic)

class Shape { public: virtual void draw(); };     // 4. virtual function
class Circle : public Shape { public: void draw(); };
Shape *s = new Circle;  s->draw();      // Circle::draw() at run time

Function / method overloading

When two or more functions in the same scope have the same name but different parameter lists (number, type or order of parameters), it is called function overloading. The compiler selects the right function by matching arguments, so it is compile-time polymorphism. The return type alone cannot distinguish overloaded functions.

// Syntax: same name, different parameters (same class)
class A {
    void show(int x);
    void show(double x);
    void show(int x, int y);
};

Function / method overriding

When a derived class redefines a function of its base class with the same name, same parameters and same return type, it is called function overriding. The derived version replaces the base version for derived objects. If the base function is declared virtual and called through a base pointer/reference, the call is resolved at run time, so it gives run-time polymorphism.

// Syntax: same signature in base and derived class
class Base {
public:
    virtual void show() { ... }
};
class Derived : public Base {
public:
    void show() override { ... }     // overrides Base::show()
};

Differences

Basis Function overloading Function overriding
Definition Same name, different parameters. Same name, same parameters, in base and derived class.
Scope Within the same class (or scope). Across base and derived classes.
Inheritance Not required. Required.
Signature Must differ. Must be the same.
Return type Can differ (but not used to overload). Must be the same (or covariant).
virtual keyword Not used. Used in base class for run-time behaviour.
Polymorphism Compile-time (static). Run-time (dynamic).
Purpose Same operation on different types of data. Change / specialise inherited behaviour.
Example area(int), area(float, float) Animal::sound() and Dog::sound()
(b)
Write a C++ program to calculate the area using method overloading that accepts input from the user and then shows the desired result.
Unit 4: Polymorphism7 marksAsked only in this paper
ANSWER

Idea: One function name area() is overloaded three times with different parameter lists: one int for a square, two float values for a rectangle and one double for a circle. The compiler chooses the correct version from the type and number of arguments.

C++ Program (compiled and tested)
#include <iostream>
using namespace std;

class Shape {
public:
    int area(int side) {                 // square
        return side * side;
    }
    float area(float l, float b) {       // rectangle
        return l * b;
    }
    double area(double r) {              // circle
        return 3.14159 * r * r;
    }
};

int main() {
    Shape s;
    int side;
    float l, b;
    double r;
    cout << "Enter side of square: ";
    cin >> side;
    cout << "Enter length and breadth of rectangle: ";
    cin >> l >> b;
    cout << "Enter radius of circle: ";
    cin >> r;
    cout << "Area of square    = " << s.area(side) << endl;    // area(int)
    cout << "Area of rectangle = " << s.area(l, b) << endl;    // area(float, float)
    cout << "Area of circle    = " << s.area(r) << endl;       // area(double)
    return 0;
}
OUTPUT
Enter side of square: 6
Enter length and breadth of rectangle: 8 4.5
Enter radius of circle: 3
Area of square    = 36
Area of rectangle = 36
Area of circle    = 28.2743

Explanation: s.area(side) matches area(int), s.area(l, b) matches area(float, float) and s.area(r) matches area(double). This selection at compile time is compile-time polymorphism through method overloading.

Question 5 14 marks

(a)
Explain the concept of multithreading in object-oriented programming approach. Write its benefits. Discuss the collection and its type. What is a collection class?
Unit 5: Strings, Exceptions, Threads & Collections7 marksAlso asked in Nov 2022, Dec 2023, Dec 2024, Dec 2025
ANSWER

Thread and multithreading

A thread is the smallest unit of execution within a process - a single sequential flow of control with its own program counter and stack. Multithreading is the ability of a program (process) to run two or more threads concurrently, so that different parts of the program execute at the same time. All threads of a process share the same memory (code and data), which makes them lightweight compared with separate processes. Example: in a word processor, one thread accepts typing, another checks spelling and a third auto-saves the file.

Multithreading in the object-oriented approach

In OOP, a thread is itself represented as an object. In Java, a thread is created by extending the Thread class or implementing the Runnable interface and overriding run(). In C++11 and later, the std::thread class (header <thread>) creates a thread object that runs a function or a member function of an object; join() waits for it to finish. Shared data is protected with synchronization objects such as std::mutex.

NewRunnableRunningTerminatedBlocked / Waitingstart()scheduler dispatchtime slice over / yieldrun endssleep / wait / I/Onotify / I/O done
Life cycle of a thread

States of a thread: New (created) → Runnable (ready, waiting for CPU) → Running (executing) → Blocked / Waiting (waiting for I/O, lock or sleep) → back to Runnable → Terminated (finished).

Importance and benefits (advantages)

  1. Better responsiveness - a program remains responsive (a GUI does not freeze) while a long task runs in another thread.
  2. Better CPU utilisation - on multi-core processors, threads run in parallel and use all cores.
  3. Resource sharing - threads share memory and files of the process, so communication between them is easy.
  4. Economy - creating and switching threads is cheaper than creating processes.
  5. Faster execution - independent tasks are done simultaneously (downloading several files together).
  6. Simplified modelling - concurrent real-world activities are modelled naturally as concurrent objects.

Problems to handle: race conditions, deadlock and starvation; they are controlled through synchronization (mutex, locks, semaphores).

Applications

Web servers handling many clients at once; GUI applications; games (rendering, sound, input in separate threads); media players and video streaming; downloading managers; banking and ATM servers processing many transactions; real-time and embedded systems; scientific simulations and parallel computing.

Program

C++ Program (compiled and tested)
#include <iostream>
#include <thread>
#include <mutex>
#include <string>
using namespace std;

mutex m;                                   // protects the shared screen (cout)

class Downloader {
public:
    void download(string file, int parts) {
        for (int i = 1; i <= parts; i++) {
            lock_guard<mutex> lock(m);     // synchronization
            cout << file << ": part " << i << "/" << parts << " done" << endl;
        }
    }
};

int main() {
    Downloader d;
    thread t1(&Downloader::download, &d, "video.mp4", 3);   // thread 1 starts
    thread t2(&Downloader::download, &d, "notes.pdf", 2);   // thread 2 starts
    t1.join();                             // main waits for t1
    t2.join();                             // main waits for t2
    cout << "All downloads finished" << endl;
    return 0;
}

One possible output (the order of lines may change on every run because threads run concurrently):

OUTPUT
video.mp4: part 1/3 done
video.mp4: part 2/3 done
video.mp4: part 3/3 done
notes.pdf: part 1/2 done
notes.pdf: part 2/2 done
All downloads finished

Data collection and collection class

A data collection is an object that groups multiple elements into a single unit so that they can be stored, retrieved and processed easily (for example a list of students or the accounts of a bank). A collection class (container class) is a class whose objects hold other objects and provide operations such as insert, delete, search, sort and traverse. In C++, collection classes are provided by the Standard Template Library (STL) as containers, used together with iterators and algorithms. In Java they are provided by the Collections Framework (ArrayList, LinkedList, HashSet, HashMap).

Types of collections in C++ (STL containers)

1. Sequence containers - store elements in a linear order: array (fixed size), vector (dynamic array), deque (double-ended queue), list (doubly linked list), forward_list (singly linked list).

2. Associative containers - store elements in sorted order using balanced trees: set (unique keys), multiset (duplicate keys), map (unique key-value pairs), multimap.

3. Unordered associative containers - use hash tables: unordered_set, unordered_map, unordered_multiset, unordered_multimap.

4. Container adapters - restricted interfaces built on other containers: stack (LIFO), queue (FIFO), priority_queue (highest priority first).

(b)
Explain library management system using object-oriented diagram.
Unit 5: Strings, Exceptions, Threads & Collections7 marksAlso asked in Dec 2024, Dec 2025
ANSWER

Library Management System (LMS)

A Library Management System is software that manages the day-to-day work of a library: keeping the record of books and members, issuing and returning books, calculating fines and searching the catalogue.

Functionalities

  1. Book management - add, update, remove and search books (by title, author, ISBN).
  2. Member management - register students / faculty, update details, issue library cards.
  3. Issue and return - issue a book if it is available and the member is within the limit; record due date; accept returns.
  4. Fine calculation - charge a fine for late return.
  5. Reservation - reserve a book that is currently issued.
  6. Reports - list of issued books, overdue books, member history.
  7. Login and roles - librarian (administrator) and member access.

Architecture (three layers)

  • Presentation layer - user interface: menus / screens for the librarian and members.
  • Business logic layer - classes Library, Book, Member, Librarian, Transaction, Fine that implement the rules.
  • Data layer - files or a database that store books, members and transactions permanently.
Librarian- empId- name+ addBook()+ issueBook()+ returnBook()Library- name- address+ addMember()+ searchBook()Book- bookId- title, author- isIssued+ getDetails()Member- memberId- name- maxBooks+ borrow()+ returnBook()Transaction- txnId- issueDate- dueDate+ calculateFine()StudentmaxBooks = 3FacultymaxBooks = 10Fine- amount- paidmanages1..*1has**hasfor*1makes1*0..1
Object-oriented (class) diagram of a library management system

Explanation of the diagram

  • Library aggregates many Book objects and many Member objects (books and members exist independently of the library software).
  • Student and Faculty inherit from Member (is-a); they differ in the maximum number of books allowed.
  • Librarian manages the library: adds books, registers members, issues and returns books.
  • Each Transaction (issue / return) is associated with one Member and one Book and has a Fine if the book is returned late (composition - the fine has no meaning without the transaction).

Use of strings, exception handling and collections

Feature Use in LMS
Strings Book title, author, member name; searching by keyword with find(); formatting reports.
Exception handling Throw exceptions for book not found, book already issued, issue limit exceeded, invalid member id; catch them and show a message without stopping the program.
Collections map<int, Book> - books by id for fast search; map<int, Member> - members; vector<int> - books issued to a member; queue<int> - reservation list; list<Transaction> - transaction log.

Program (core of LMS)

C++ Program (compiled and tested)
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <stdexcept>
using namespace std;

class Book {
public:
    int id;
    string title, author;
    bool issued = false;
    Book(int i, string t, string a) : id(i), title(t), author(a) {}
};

class Member {
public:
    int id;
    string name;
    vector<int> borrowed;                         // ids of borrowed books
    Member(int i, string n) : id(i), name(n) {}
};

class Library {
    map<int, Book> books;                         // collection: id -> Book
    map<int, Member> members;                     // collection: id -> Member
public:
    void addBook(Book b)     { books.emplace(b.id, b); }
    void addMember(Member m) { members.emplace(m.id, m); }

    void issueBook(int memberId, int bookId) {
        if (!books.count(bookId))     throw invalid_argument("Book not found");
        if (!members.count(memberId)) throw invalid_argument("Member not found");
        Book &b = books.at(bookId);
        if (b.issued) throw runtime_error("'" + b.title + "' is already issued");
        b.issued = true;
        members.at(memberId).borrowed.push_back(bookId);
        cout << members.at(memberId).name << " issued '" << b.title << "'" << endl;
    }
    void searchByAuthor(string key) {             // string handling
        for (auto &p : books)
            if (p.second.author.find(key) != string::npos)
                cout << "Found: " << p.second.title << " by " << p.second.author << endl;
    }
};

int main() {
    Library lib;
    lib.addBook(Book(1, "C++ Basics", "R. Sharma"));
    lib.addBook(Book(2, "OOP Concepts", "S. Verma"));
    lib.addMember(Member(10, "Ritu"));
    lib.addMember(Member(11, "Sameer"));
    try {
        lib.issueBook(10, 2);
        lib.issueBook(11, 2);                     // same book again
    }
    catch (exception &e) {                        // exception handling
        cout << "Error: " << e.what() << endl;
    }
    lib.searchByAuthor("Sharma");
    return 0;
}
OUTPUT
Ritu issued 'OOP Concepts'
Error: 'OOP Concepts' is already issued
Found: C++ Basics by R. Sharma

Question 6 14 marks

(a)
What is exception? Write a program to read three numbers x, y and z and evaluate R given by R = z / (x - y). Use exception handling to throw an exception in case division by zero is attempted.
Unit 5: Strings, Exceptions, Threads & Collections7 marksAlso asked in Nov 2022, Dec 2023, Dec 2025
ANSWER

Exception

An exception is an unusual condition or run-time error that occurs during the execution of a program and disturbs its normal flow. Examples: division by zero, array index out of range, file not found, insufficient memory, invalid input.

  • Synchronous exceptions - caused by the program itself (divide by zero, out-of-range index); C++ exception handling deals with these.
  • Asynchronous exceptions - caused by events outside the program (keyboard interrupt, hardware failure).

Logic: If x - y is zero the denominator becomes zero. Before dividing, the program checks the denominator inside a try block; if it is zero it throws the value, which is caught by a catch(float) block. Otherwise R is calculated and printed.

C++ Program (compiled and tested)
#include <iostream>
using namespace std;

int main() {
    float x, y, z, R;
    cout << "Enter x, y and z: ";
    cin >> x >> y >> z;
    try {
        if (x - y == 0)
            throw (x - y);               // throw when denominator is zero
        R = z / (x - y);
        cout << "R = " << R << endl;
    }
    catch (float d) {                    // handler for float exception
        cout << "Exception caught: division by zero (x - y = " << d << ")" << endl;
    }
    cout << "End of program" << endl;
    return 0;
}

Output (run 1 - valid values):

OUTPUT
Enter x, y and z: 10 5 20
R = 4
End of program

Output (run 2 - division by zero):

OUTPUT
Enter x, y and z: 7 7 15
Exception caught: division by zero (x - y = 0)
End of program

Explanation: For x = 10, y = 5, z = 20 → R = 20 / 5 = 4. For x = 7, y = 7 the denominator is 0, so throw (x - y); transfers control to the catch block; the division statement is skipped and the program ends normally.

(b)
Discuss the methods of passing an argument in C++. Explain with suitable program.
Unit 1: Introduction to OOP7 marksAsked only in this paper
ANSWER

When a function is called, the values supplied in the call are called actual arguments and the variables that receive them in the function definition are called formal arguments. C++ provides three methods of passing arguments.

1. Call by value

A copy of the actual argument is passed. Changes made to the formal argument inside the function do not affect the actual argument. It is safe but copying large objects is costly.

void swapByValue(int a, int b);          // call: swapByValue(x, y);

2. Call by address (pointer)

The address of the actual argument is passed and received in a pointer. The function works on the original variable through the pointer, so changes are reflected in the caller.

void swapByAddress(int *a, int *b);      // call: swapByAddress(&x, &y);

3. Call by reference

A reference (alias) of the actual argument is passed. The formal argument becomes another name for the same memory location, so changes are reflected, and the syntax stays as simple as call by value. Passing objects as const references avoids copying while preventing modification.

void swapByReference(int &a, int &b);    // call: swapByReference(x, y);

Program

C++ Program (compiled and tested)
#include <iostream>
using namespace std;

void swapByValue(int a, int b) {         // copies of x, y are received
    int t = a; a = b; b = t;
}
void swapByAddress(int *a, int *b) {     // addresses of x, y are received
    int t = *a; *a = *b; *b = t;
}
void swapByReference(int &a, int &b) {   // a, b are alias names of x, y
    int t = a; a = b; b = t;
}

int main() {
    int x = 10, y = 20;
    swapByValue(x, y);
    cout << "After call by value     : x = " << x << ", y = " << y << endl;
    swapByAddress(&x, &y);
    cout << "After call by address   : x = " << x << ", y = " << y << endl;
    swapByReference(x, y);
    cout << "After call by reference : x = " << x << ", y = " << y << endl;
    return 0;
}
OUTPUT
After call by value     : x = 10, y = 20
After call by address   : x = 20, y = 10
After call by reference : x = 10, y = 20

Explanation: The call by value swaps only the copies, so x and y remain 10 and 20. The call by address swaps the originals (20, 10). The call by reference swaps them again (10, 20).

Basis Call by value Call by address Call by reference
What is passed Copy of value Address of variable Alias of variable
Formal argument Ordinary variable Pointer (int *) Reference (int &)
Effect on actual argument No change Changed Changed
Memory Extra copy made Pointer only No copy
Call syntax f(x) f(&x) f(x)

Default arguments: C++ also allows default values, e.g. float interest(float p, float r = 7.5); can be called as interest(1000).

Question 7 14 marks

(a)
Write a program to create a file called Emp.dat with employee number, name, salary, department, deductions, and allowances as per record fields. Open a file, read the record. Calculate the net salary and write it back to the same file.
Unit 1: Introduction to OOP7 marksAsked only in this paper
ANSWER

Logic:

  1. Define a class Employee with the record fields and a field netSalary.
  2. Create Emp.dat in binary mode with ofstream and write each employee object with write().
  3. Re-open the same file with fstream in ios::in | ios::out | ios::binary mode.
  4. For every record: remember its position with tellg(), read() the record, calculate Net salary = Salary + Allowances - Deductions, move back with seekp() and write() the updated record at the same place.
  5. Read the file again and display the records to verify.
C++ Program (compiled and tested)
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

class Employee {
    int empNo;
    char name[20], dept[15];
    double salary, allowances, deductions, netSalary;
public:
    void input() {
        cout << "Enter Emp No, Name, Department: ";
        cin >> empNo >> name >> dept;
        cout << "Enter Salary, Allowances, Deductions: ";
        cin >> salary >> allowances >> deductions;
        netSalary = 0;                         // not calculated yet
    }
    void calculateNet() {
        netSalary = salary + allowances - deductions;
    }
    void display() {
        cout << setw(6) << empNo << setw(10) << name << setw(8) << dept
             << setw(10) << salary << setw(10) << netSalary << endl;
    }
};

int main() {
    Employee e;
    int n;

    // Step 1: create Emp.dat and store the records
    ofstream fout("Emp.dat", ios::binary);
    cout << "How many employees? ";
    cin >> n;
    for (int i = 0; i < n; i++) {
        e.input();
        fout.write((char *)&e, sizeof(e));
    }
    fout.close();

    // Step 2: open the same file for reading + writing
    fstream file("Emp.dat", ios::in | ios::out | ios::binary);
    streampos pos = file.tellg();              // start of first record
    while (file.read((char *)&e, sizeof(e))) {
        e.calculateNet();                      // calculate net salary
        file.seekp(pos);                       // go back to this record
        file.write((char *)&e, sizeof(e));     // write it back to same file
        pos = file.tellp();                    // start of next record
        file.seekg(pos);
    }
    file.close();

    // Step 3: read the updated file and display
    ifstream fin("Emp.dat", ios::binary);
    cout << "\n EmpNo      Name    Dept    Salary  NetSalary" << endl;
    while (fin.read((char *)&e, sizeof(e)))
        e.display();
    fin.close();
    return 0;
}
OUTPUT
How many employees? 2
Enter Emp No, Name, Department: 101 Ankit HR
Enter Salary, Allowances, Deductions: 30000 5000 2000
Enter Emp No, Name, Department: 102 Pooja IT
Enter Salary, Allowances, Deductions: 45000 8000 3500

 EmpNo      Name    Dept    Salary  NetSalary
   101     Ankit      HR     30000     33000
   102     Pooja      IT     45000     49500

Explanation: seekp(pos) places the put pointer at the beginning of the record just read, so write() overwrites that same record with the calculated net salary. Because the record size is fixed (sizeof(e)), every record can be updated in place without disturbing the others.

(b)
What are the functions supported by file stream classes for performing I/O operations?
Unit 1: Introduction to OOP7 marksAlso asked in Nov 2022
ANSWER

File handling

A file is a collection of related data stored permanently on a secondary storage device. File handling is the mechanism of creating, opening, reading, writing and closing files from a program, so that data is not lost when the program ends (persistence). In C++, file I/O is done through stream classes declared in the header <fstream>.

iosistreamostreamiostreamifstreamfstreamofstreamfstreambase(provides open(), close())Shaded classes are declared in <fstream>; arrows point from derived class to base class.
File stream class hierarchy in C++
Class Purpose
ifstream Input file stream; reads data from a file (inherits istream).
ofstream Output file stream; writes data to a file (inherits ostream).
fstream Both reading and writing (inherits iostream).
filebuf / fstreambase Provide the file buffer and common operations such as open() and close().

Steps: (1) include <fstream>, (2) create a stream object, (3) open the file, (4) read/write, (5) close the file.

File opening modes: ios::in (read), ios::out (write), ios::app (append at end), ios::ate (go to end on opening), ios::trunc (delete old contents), ios::binary (binary mode). Modes can be combined with |, e.g. fstream f("a.dat", ios::in | ios::out | ios::binary);

Functions supported by file stream classes

Function Work
open() / close() Opens a file in a given mode / closes it and flushes the buffer.
is_open() Returns true if the file was opened successfully.
put(ch) Writes a single character to the file.
get(ch) Reads a single character from the file.
getline(stream, str) Reads a complete line of text.
write((char*)&obj, size) Writes a block of binary data (for example a whole object).
read((char*)&obj, size) Reads a block of binary data into memory.
seekg(pos, dir) Moves the get (read) pointer; dir = ios::beg, ios::cur, ios::end.
seekp(pos, dir) Moves the put (write) pointer.
tellg() / tellp() Returns the current position of the get / put pointer.
eof() Returns true when the end of file is reached.
fail(), bad(), good(), clear() Check and reset the error state of the stream.
<< and >> Formatted write and read, exactly as with cout and cin.

Program: using the file stream functions

C++ Program (compiled and tested)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream out("demo.txt");             // open file for writing
    out << "OOP in C++\n";                // << insertion operator
    out.put('A');                         // put(): writes one character
    out.put('\n');
    out.write("Line by write()\n", 16);   // write(): writes a block of bytes
    out.close();                          // close(): closes the file

    ifstream in("demo.txt");              // open file for reading
    if (!in.is_open()) {                  // is_open(): checks success
        cout << "File not found";
        return 1;
    }
    string line;
    getline(in, line);                    // getline(): reads one line
    cout << "getline() : " << line << endl;
    char ch;
    in.get(ch);                           // get(): reads one character
    cout << "get()     : " << ch << endl;

    in.seekg(0, ios::end);                // seekg(): move get pointer to end
    cout << "tellg()   : file size = " << in.tellg() << " bytes" << endl;
    in.seekg(0, ios::beg);                // back to the beginning

    cout << "Full file :" << endl;
    while (in.get(ch))                    // loop stops at eof()
        cout << ch;
    in.close();
    return 0;
}
OUTPUT
getline() : OOP in C++
get()     : A
tellg()   : file size = 29 bytes
Full file :
OOP in C++
A
Line by write()

Question 8 14 marks

Write short notes on (any two):

(a)
Ambiguity in Multiple inheritance
Unit 3: Inheritance & Relationships7 marks each (any two)Also asked in Nov 2022
ANSWER

When does ambiguity arise?

In multiple inheritance a derived class has more than one base class. Ambiguity arises in two situations:

1. Same member name in two base classes - if both base classes have a member with the same name (for example input()), the call obj.input() is ambiguous, because the compiler cannot decide which version to use.

2. Diamond problem (multipath inheritance) - when two base classes are themselves derived from a common grandparent, the derived class receives two copies of the grandparent's members (two name, two age). Any access to them is ambiguous.

Personname, ageStudentrollno, marksEmployeeempcode, designationWorkingStudentall six itemsvirtualvirtualWithout virtual:WorkingStudent gets TWOcopies of name and age.With virtual base class:only ONE shared copy.
Diamond problem: WorkingStudent gets Person through two paths

How to resolve the ambiguity

  1. Scope resolution operator (::) - specify the class explicitly: obj.Student::input();
  2. Function overriding - define the function again in the derived class; the derived version hides both base versions and can call them explicitly.
  3. Virtual base class - declare the common base as virtual in the intermediate classes: class Student : virtual public Person. Then only one shared copy of Person is inherited, which removes the diamond problem.
(b)
Object Model
Unit 1: Introduction to OOP7 marks each (any two)Also asked in Dec 2023, Dec 2025
ANSWER

Object Model

The object model is the conceptual framework of object-oriented development. It describes a system as a collection of objects that have state, behaviour and identity, are created from classes, and are connected to one another through relationships (association, aggregation, inheritance). In design methods such as OMT, the object model shows the static structure of the system - classes, their attributes, operations and relationships - drawn as class and object diagrams.

Basic elements of the object model (Grady Booch)

Four major elements (a model without any of these is not object-oriented):

  1. Abstraction - Focuses on the essential characteristics of an object relative to the viewer and ignores irrelevant details.
  2. Encapsulation - Hides the internal implementation of an object and exposes only its interface; achieved by classes and access specifiers.
  3. Modularity - Decomposes the system into a set of cohesive, loosely coupled modules (classes, files, packages).
  4. Hierarchy - Ranking or ordering of abstractions: "is-a" hierarchy (inheritance) and "part-of" hierarchy (aggregation).

Three minor elements (useful but not essential):

  1. Typing - Enforcement of the class of an object, so that objects of different types cannot be interchanged freely (strong typing in C++).
  2. Concurrency - The property that allows several objects to be active at the same time (threads).
  3. Persistence - The property by which an object continues to exist after its creator stops (data saved in files or databases).

The building blocks used in every object model are classes, objects, attributes, operations (methods), messages and relationships.

(c)
Access specifier in C++
Unit 2: Classes, Encapsulation & Abstraction7 marks each (any two)Also asked in Nov 2022, Dec 2023, Dec 2024, Dec 2025
ANSWER

Access modifiers

Access modifiers (access specifiers) are keywords that decide which parts of a program can access the members (data and functions) of a class. They are the main tool for implementing data hiding and encapsulation. C++ provides three access modifiers: private, protected and public.

1. private - Members declared private can be accessed only by the member functions (and friends) of the same class. They are not accessible from outside the class or from derived classes. By default, all members of a class are private. Data members are normally made private.

2. protected - Members declared protected are accessible within the class and in its derived classes, but not from outside (for example from main()). It is used when a base class wants to share data only with its children.

3. public - Members declared public are accessible from anywhere in the program through an object. Member functions that form the interface of the class are made public. By default, members of a struct are public.

class Demo {
private:   int a;       // only Demo
protected: int b;       // Demo + derived classes
public:    int c;       // everyone
};

Comparison of access levels

Accessible from private protected public
Member functions of the same class Yes Yes Yes
Friend functions / classes Yes Yes Yes
Member functions of a derived class No Yes Yes
Outside the class (e.g. main()) through an object No No Yes
Typical use Data members Data shared with child classes Interface functions

Answers are written for 7-mark questions in exam style. Every C++ program was compiled and run; the output shown is the real output.

Advertisement

💬 Comments & Doubts

💭

Abhi tak koi comment nahi

Sabse pehle comment karne wale bano!

Apna comment likhein

Doubt ho ya suggestion — kuch bhi poochh sakte hain. Login zaroori nahi hai.

7 × 3 =

Ye sirf ye confirm karne ke liye hai ki aap robot nahi hain.

Comment publish hone se pehle admin check karta hai.

🔒 Content copy nahi kar sakte