Welcome to Edugrown – Your Learning Partner EduGrown
🕑 Aaj 1 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 | Nov 2022

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

Advertisement
CS/CT/CO-305 (GS) · RGPV Bhopal
Object Oriented Programming & Methodology
B.Tech., III Semester · Examination, November 2022 · 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 What is OOP? Features of OOP ★
b Relationships among classes
Q2
a Classes & objects ★
b Constructors & destructors ★
Q3
a Association vs aggregation vs composition ★
b Access modifiers ★
Q4
a Constructors & destructors ★
b Overloading vs overriding ★
Q5
a Operator overloading: Distance
b Strings & string functions ★
Q6
a Ambiguity in multiple inheritance ★
b Interfaces & abstract classes ★
Q7
a Exception handling ★
b Polymorphism & its types ★
Q8
i Virtual vs pure virtual function ★
ii File handling & stream functions ★
iii Data collections (ATM case study) ★
15 of 17 parts (★) were also asked in other years. Marks by unit (out of 112 offered):
U1 11.7
U2 28
U3 28
U4 25.7
U5 18.7
Unit 1: Introduction to OOPUnit 2: Classes, Encapsulation & AbstractionUnit 3: Inheritance & RelationshipsUnit 4: PolymorphismUnit 5: Strings, Exceptions, Threads & Collections

Question 1 14 marks

(a)
What is Object Oriented Programming? Write merits and demerits of OOPs and also write applications of object-oriented programming.
Unit 1: Introduction to OOP7 marksAlso asked in Jun 2023, 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

Merits (Advantages) of OO Methodology

  1. Reusability - Through inheritance, existing classes are reused to build new classes, which saves development time and cost.
  2. Data security - Data hiding and encapsulation protect data from accidental or unauthorised modification.
  3. Modularity - The program is divided into independent objects, so each module can be developed and tested separately.
  4. Easy maintenance and modification - A change inside one class does not affect other parts of the program as long as its interface is unchanged.
  5. Real-world modelling - Objects map directly to real entities (student, account, book), which makes analysis and design natural.
  6. Extensibility - New features are added by creating new classes or derived classes without rewriting existing code.
  7. Polymorphism and flexibility - One interface can work with many types of objects, which makes the code flexible.
  8. Reduced complexity - Abstraction hides unnecessary details, so large systems become easier to understand.
  9. Team development - Different programmers can work on different classes at the same time.
  10. Better productivity - Class libraries (such as the STL) allow rapid development.

Demerits of OO Methodology

  1. Larger program size - OOP programs usually contain more lines of code and generate larger executables.
  2. Slower execution - Features such as dynamic binding and object creation add run-time overhead.
  3. Steep learning curve - Thinking in terms of objects, classes and hierarchies requires training and experience.
  4. Careful design required - A poor class design (wrong hierarchy) is hard to correct later.
  5. More memory - Objects, virtual tables and extra function calls consume more memory.
  6. Not suitable for every problem - Small, purely computational tasks do not benefit from objects.

Applications of OOP

Real-time systems; simulation and modelling; object-oriented databases; graphical user interfaces (GUI) and window systems; computer games; CAD/CAM systems; AI and expert systems; hypertext and hypermedia; neural networks; office automation and decision support systems; banking, ERP and e-commerce software; mobile applications.

Real-world scenarios

OOP is beneficial OOP may not be ideal
Banking system - Account, Customer, Transaction become classes; data hiding protects balances. Small scripts - a 20-line script to rename files is simpler in procedural style.
Games - Player, Enemy, Weapon share a base class; polymorphism controls behaviour. Embedded / low-memory devices - overhead of objects and virtual calls may not fit tight memory or timing limits.
GUI applications - Button, TextBox, Window inherit from a common Widget class. High-performance numeric code - matrix or scientific computation is often written in procedural or data-oriented style for speed.
Hospital / library management - entities and their relationships map naturally to objects. Data pipelines and stateless processing - functional or procedural style is clearer when data simply flows through steps.

Exam tip: Write at least 6 merits and 4 demerits with one line each, then add 5 to 6 applications. For the Dec 2024 version, finish with the two-column table of scenarios.

(b)
What are the different kinds of relationship among classes? Explain.
Unit 3: Inheritance & Relationships7 marksAsked only in this paper
ANSWER

In an object-oriented system, classes do not work alone; they are connected by relationships. The main kinds of relationships among classes are:

Inheritanceis-aCarVehicleAssociationuses-aDoctorPatientAggregationhas-a (weak)TeacherDepartmentCompositionpart-of (strong)EngineCarDependencyuses temporarilyPrinterDocumentRealizationimplementsCircleDrawablechild → parentdiamond at the wholediamond at the wholeclass → interface
UML notation for relationships among classes

1. Inheritance (Generalization) - "is-a": one class is a special kind of another class. Example: Car is a Vehicle. Notation: solid line with a hollow triangle pointing to the base class.

2. Association - "uses-a / knows-a": a structural link between two independent classes whose objects work together. Example: a Doctor treats a Patient; a Teacher teaches a Student. Notation: solid line, optionally with multiplicity (1, *, 0..1).

3. Aggregation - "has-a" (weak): a special association in which one class is a whole and the other is a part, but the part can exist independently of the whole. Example: a Department has Teachers; if the department closes, teachers still exist. Notation: hollow diamond at the whole.

4. Composition - "part-of" (strong): a strong form of aggregation in which the part cannot exist without the whole; their lifetimes are the same. Example: a House and its Rooms; a Car and its Engine. Notation: filled diamond at the whole.

5. Dependency - "uses temporarily": one class uses another only for a short time, for example as a function parameter or local variable; a change in one may affect the other. Example: Printer uses a Document in print(Document d). Notation: dashed arrow.

6. Realization - "implements": a class implements the behaviour declared by an interface (abstract class). Example: Circle realizes the Drawable interface. Notation: dashed line with hollow triangle.

Relationship Meaning Strength Example
Inheritance is-a Strong (class level) Dog is an Animal
Composition part-of, same lifetime Strongest object link Car - Engine
Aggregation has-a, independent parts Medium Department - Teacher
Association uses / knows Weak Doctor - Patient
Dependency uses temporarily Weakest Printer - Document
Realization implements Contract Circle - Drawable

Question 2 14 marks

(a)
What do you mean by the term class and object? What is the relation and difference between these two? Write an example (syntax) to define a class in C++. Explain state, behavior, and identity of object in brief.
Unit 2: Classes, Encapsulation & Abstraction7 marksAlso asked in Dec 2024, Dec 2025
ANSWER

Class

A class is a user-defined data type that binds data members (attributes) and member functions (methods) into a single unit. It is a blueprint or template from which objects are created. A class does not occupy memory for its data until an object is created.

Object

An object is an instance of a class. It is a real, run-time entity that occupies memory and has its own copy of the data members. Many objects can be created from one class.

Syntax to define a class in C++

class ClassName {
private:
    // data members (hidden)
protected:
    // members visible to derived classes
public:
    // member functions (interface)
};                       // semicolon is compulsory

ClassName obj1, obj2;    // creating objects

Example:

class Student {
private:
    int rollNo;                     // attributes (state)
    char name[30];
public:
    void getData()  { cin >> rollNo >> name; }      // behaviour
    void showData() { cout << rollNo << " " << name; }
};
Student s1, s2;                     // s1 and s2 are objects
s1.getData();  s1.showData();       // accessing members with dot operator
Student (class)- rollNo : int- name : string+ getData()+ showData()s1 : StudentrollNo = 101name = "Aman"s2 : StudentrollNo = 102name = "Priya"s3 : StudentrollNo = 103name = "Rohit"creates objects (instantiation)Blueprint: no memory for dataInstances: each has its own data
One class acts as a template for many objects

Relation between class and object

A class is the logical description; an object is its physical realisation. The relation is like that of a house plan and the houses built from it, or a cookie cutter and cookies. Every object belongs to exactly one class, and one class can have any number of objects.

Class Object
Blueprint / template / logical entity. Instance / physical entity.
Declared once using keyword class. Created many times: Student s1, s2;
Does not occupy memory for data. Occupies memory when created.
Defines what data and functions objects will have. Holds actual values and calls the functions.
Example: Car, Student. Example: myCar, s1.

Identifying classes

Classes are identified from the problem statement by noun-phrase analysis:

  1. Underline the nouns in the requirement; they are candidate classes (Student, Book, Library, Account).
  2. Verbs become methods (issue, return, deposit), and adjectives / properties become attributes (name, price).
  3. Keep a candidate only if it has its own state and behaviour, is relevant to the problem and may have many instances.
  4. Remove candidates that are redundant (Client = Customer), vague (System), only an attribute (name) or only an operation (payment as an action).

Example: "A student borrows books from the library." → classes Student, Book, Library; method borrow().

State, behaviour and identity of an object

Property Meaning Example: object myCar
State The values of the object's attributes at a given moment. colour = red, speed = 60 km/h, fuel = 20 L
Behaviour What the object can do; its methods and how it responds to messages. start(), accelerate(), brake()
Identity The property that distinguishes one object from all others, even if their states are equal (its name / memory address). myCar and yourCar are different objects even with the same colour
(b)
Discuss construction and destruction of an object. Write a program to explain it.
Unit 2: Classes, Encapsulation & Abstraction7 marksAlso asked in Dec 2023
ANSWER

Constructor

A constructor is a special member function that is called automatically when an object is created. Its role is to initialise the data members of the object (and to allocate resources if needed).

Characteristics: it has the same name as the class; it has no return type, not even void; it is declared in the public section; it can be overloaded and can have default arguments; it cannot be virtual; if no constructor is written, the compiler supplies a default one.

Destructor

A destructor is a special member function that is called automatically when an object is destroyed (goes out of scope or is deleted). Its role is to release resources such as memory, files or connections held by the object.

Characteristics: same name as the class preceded by a tilde (~); no return type and no arguments; it cannot be overloaded (only one per class); it can be virtual; objects are destroyed in the reverse order of their creation.

~Box() { cout << "Object destroyed"; }

Construction and destruction of an object

  • Construction: memory is allocated for the object (on the stack, in static memory or on the heap with new), and then the constructor initialises it.
  • Destruction: when the object's lifetime ends - at the end of its block for local objects, at delete for dynamic objects, at program end for global/static objects - the destructor runs and then the memory is released.
C++ Program (compiled and tested)
#include <iostream>
#include <string>
using namespace std;

class Box {
    string name;
    int length;
public:
    Box() {                                   // default constructor
        name = "Default";
        length = 1;
        cout << "Default constructor : " << name << endl;
    }
    Box(string n, int l) {                    // parameterized constructor
        name = n;
        length = l;
        cout << "Parameterized constr: " << name << endl;
    }
    Box(const Box &b) {                       // copy constructor
        name = b.name + "-copy";
        length = b.length;
        cout << "Copy constructor    : " << name << endl;
    }
    ~Box() {                                  // destructor
        cout << "Destructor          : " << name << endl;
    }
};

int main() {
    Box b1;                        // default constructor
    Box b2("Small", 5);            // parameterized constructor
    Box b3(b2);                    // copy constructor
    {
        Box temp("Temp", 2);       // object created inside a block
    }                              // temp destroyed at end of its scope
    Box *p = new Box("Heap", 9);   // dynamic object
    delete p;                      // destructor called by delete
    cout << "End of main" << endl;
    return 0;                      // b3, b2, b1 destroyed in reverse order
}
OUTPUT
Default constructor : Default
Parameterized constr: Small
Copy constructor    : Small-copy
Parameterized constr: Temp
Destructor          : Temp
Parameterized constr: Heap
Destructor          : Heap
End of main
Destructor          : Small-copy
Destructor          : Small
Destructor          : Default

Explanation: temp is destroyed as soon as its block ends; the heap object is destroyed only when delete is called; the remaining objects b3, b2, b1 are destroyed at the end of main() in reverse order of creation.

Question 3 14 marks

(a)
Explain the concept of association and aggregation in object-oriented approach. What is Abstract class? Why Abstract classes are used?
Unit 3: Inheritance & Relationships7 marksAlso asked in Dec 2023, Dec 2024, Dec 2025
ANSWER

Association

A general "uses-a" relationship between two independent classes. Objects are linked but no ownership exists. Real-world example: a Doctor treats Patients; a Teacher teaches Students.

Aggregation

Aggregation is a special form of association that represents a "has-a" (whole-part) relationship where the part can exist independently of the whole. The whole only refers to the parts; it does not create or destroy them. It is a weak form of ownership. Real-world example: a Department has Teachers - if the department is closed, the teachers still exist; a Library has Books; a Team has Players.

Composition

Composition is a strong form of aggregation, a "part-of" relationship in which the part cannot exist without the whole. The whole creates and destroys its parts, so both have the same lifetime. Real-world example: a Car has an Engine built into it; a House has Rooms; a Human has a Heart.

Aggregation (weak has-a)Composition (strong part-of)DepartmentTeacher1..*CarEngine1Teacher exists even if the Department is closed.Engine is created and destroyed with the Car.
Aggregation (hollow diamond) and composition (filled diamond)

Differences

Basis Association Aggregation Composition
Relationship uses-a / knows-a has-a (whole-part) part-of (strong whole-part)
Ownership None Weak ownership Strong ownership
Lifetime Independent Part lives independently of whole Part dies with the whole
Dependency Lowest Medium Highest
UML symbol Plain line Hollow diamond ◇ at whole Filled diamond ◆ at whole
C++ implementation Pointer / reference / parameter Pointer or reference to an external object Member object created inside the class
Example Doctor - Patient Department - Teacher Car - Engine

Implementing aggregation (and composition) in C++

  • Aggregation: the whole class stores a pointer or reference to a part that is created outside it. Deleting the whole does not delete the part.
  • Composition: the whole class contains the part as a member object, so the part is created and destroyed together with the whole.
C++ Program (compiled and tested)
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Teacher {                              // part (aggregation)
    string name;
public:
    Teacher(string n) { name = n; }
    string getName() { return name; }
};

class Department {                           // whole: Department HAS-A Teacher
    string title;
    vector<Teacher *> staff;                 // only addresses are stored
public:
    Department(string t) { title = t; }
    void addTeacher(Teacher *t) { staff.push_back(t); }
    void show() {
        cout << title << " department: ";
        for (Teacher *t : staff) cout << t->getName() << " ";
        cout << endl;
    }
};

class Engine {                               // part (composition)
public:
    Engine()  { cout << "Engine created" << endl; }
    ~Engine() { cout << "Engine destroyed" << endl; }
};

class Car {                                  // whole: Car OWNS an Engine
    Engine engine;                           // Engine object lives inside Car
public:
    Car()  { cout << "Car created" << endl; }
    ~Car() { cout << "Car destroyed" << endl; }
};

int main() {
    Teacher t1("Gupta"), t2("Khan");         // teachers exist independently
    {
        Department cs("CSE");
        cs.addTeacher(&t1);
        cs.addTeacher(&t2);
        cs.show();
    }                                        // department closed...
    cout << t1.getName() << " still exists" << endl;   // ...teacher survives
    {
        Car c;                               // engine created with car
    }                                        // engine destroyed with car
    return 0;
}
OUTPUT
CSE department: Gupta Khan 
Gupta still exists
Engine created
Car created
Car destroyed
Engine destroyed

Explanation: Teacher Gupta continues to exist after the Department object is destroyed → aggregation. The Engine is created before the Car body and destroyed right after it → composition (same lifetime).

Abstract class

An abstract class is a class that is designed only to act as a base class and cannot be instantiated (no object of it can be created). In C++, a class becomes abstract when it contains at least one pure virtual function.

A pure virtual function is a virtual function that has no definition in the base class and is equated to zero:

virtual float area() = 0;          // pure virtual function

Rules / characteristics

  1. Objects of an abstract class cannot be created, but pointers and references to it can be created.
  2. Every derived class must override all pure virtual functions; otherwise it also becomes abstract.
  3. An abstract class may also contain data members, constructors and normal (defined) functions.
  4. It is used to achieve run-time polymorphism.

Why abstract classes are used

  • To provide a common interface for a group of related classes (all shapes must have area()).
  • To force derived classes to implement certain functions.
  • To share common code and data among derived classes while leaving specific details to them.
  • To prevent the creation of incomplete, meaningless objects (a general "Shape" has no area).
  • To support run-time polymorphism through base-class pointers and to design extensible frameworks.

How to implement an abstract class in C++

  1. Declare a base class with at least one pure virtual function (= 0).
  2. Derive concrete classes from it and override every pure virtual function.
  3. Use a base-class pointer or reference to call the functions of derived objects.
C++ Program (compiled and tested)
#include <iostream>
using namespace std;

class Shape {                              // abstract class
public:
    virtual float area() = 0;              // pure virtual function
    void show() {                          // normal function is allowed
        cout << "Area = " << area() << endl;
    }
    virtual ~Shape() {}
};

class Circle : public Shape {
    float r;
public:
    Circle(float x) { r = x; }
    float area() { return 3.14f * r * r; }    // must override
};

class Square : public Shape {
    float s;
public:
    Square(float x) { s = x; }
    float area() { return s * s; }            // must override
};

int main() {
    // Shape s;                  // ERROR: object of abstract class not allowed
    Shape *p;                    // pointer of abstract class is allowed
    Circle c(2);
    Square sq(4);
    p = &c;
    p->show();
    p = &sq;
    p->show();
    return 0;
}
OUTPUT
Area = 12.56
Area = 16

Shape is abstract because area() is pure virtual. Circle and Square give their own area(), and the common function show() written once in Shape works for both.

(b)
What are the access modifiers? How many types of access modifiers are available in C++? Explain each one in detail and their role in implementing the data hiding in object-oriented programming.
Unit 2: Classes, Encapsulation & Abstraction7 marksAlso asked in Jun 2023, 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

Effect on inheritance (visibility mode)

Base member public inheritance protected inheritance private inheritance
public public protected private
protected protected protected private
private not accessible not accessible not accessible

Private members of the base class are present in the derived object but can never be accessed directly by the derived class.

Role in class design and data hiding

  1. Data hiding - making data members private prevents direct, invalid modification (for example a negative balance).
  2. Controlled access - data is read or changed only through public getter/setter functions that can validate values.
  3. Clear interface - public members tell the user what the class offers; private members hide how it works.
  4. Safe inheritance - protected members let derived classes reuse data without exposing it to the whole program.
  5. Easy maintenance - private implementation can change without affecting the code that uses the class.

Program

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

class Account {
private:
    int pin = 1234;                   // only members of Account can use it
protected:
    double balance = 5000;            // Account + its derived classes
public:
    string holder = "Neha";           // accessible everywhere
    bool checkPin(int p) {            // private data used inside the class
        return p == pin;
    }
};

class SavingsAccount : public Account {
public:
    void addInterest() {
        balance = balance + balance * 0.04;   // OK: protected is visible
        // pin = 0;                           // ERROR: private is not visible
        cout << "Balance after interest = " << balance << endl;
    }
};

int main() {
    SavingsAccount s;
    cout << "Holder: " << s.holder << endl;                  // OK: public
    cout << "PIN correct? " << (s.checkPin(1234) ? "Yes" : "No") << endl;
    s.addInterest();
    // s.balance = 0;                 // ERROR: protected
    // s.pin = 0;                     // ERROR: private
    return 0;
}
OUTPUT
Holder: Neha
PIN correct? Yes
Balance after interest = 5200

Question 4 14 marks

(a)
Explain the role of constructor and destructor in a class. What are the different types of constructors in C++? Write the appropriate syntax for the copy constructor and parameterized constructors.
Unit 2: Classes, Encapsulation & Abstraction7 marksAlso asked in Dec 2023
ANSWER

Constructor

A constructor is a special member function that is called automatically when an object is created. Its role is to initialise the data members of the object (and to allocate resources if needed).

Characteristics: it has the same name as the class; it has no return type, not even void; it is declared in the public section; it can be overloaded and can have default arguments; it cannot be virtual; if no constructor is written, the compiler supplies a default one.

Types of constructors

  1. Default constructor - takes no arguments. Box() { length = 1; }
  2. Parameterized constructor - takes arguments, so different objects can be initialised with different values.
  3. Copy constructor - creates a new object as a copy of an existing object of the same class; it takes a reference to an object of its own class.
  4. Constructor with default arguments - Box(int l = 1); works as both default and parameterized.
  5. Dynamic constructor - allocates memory with new inside the constructor.
  6. Constructor overloading - a class can have more than one constructor with different parameter lists.

Syntax:

class Box {
    int length;
public:
    Box(int l) { length = l; }                    // parameterized constructor
    Box(const Box &b) { length = b.length; }      // copy constructor
};
Box b1(10);        // calls parameterized constructor
Box b2(b1);        // calls copy constructor   (also: Box b2 = b1;)

Destructor

A destructor is a special member function that is called automatically when an object is destroyed (goes out of scope or is deleted). Its role is to release resources such as memory, files or connections held by the object.

Characteristics: same name as the class preceded by a tilde (~); no return type and no arguments; it cannot be overloaded (only one per class); it can be virtual; objects are destroyed in the reverse order of their creation.

~Box() { cout << "Object destroyed"; }
(b)
Explain method overloading and method overriding with example.
Unit 4: Polymorphism7 marksAlso asked in Jun 2023, Dec 2023, Dec 2025
ANSWER

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()

Program

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

class Printer {                                       // OVERLOADING
public:
    void print(int x)    { cout << "Integer: " << x << endl; }
    void print(double x) { cout << "Double : " << x << endl; }
    void print(string s) { cout << "String : " << s << endl; }
};

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

int main() {
    Printer p;
    p.print(10);
    p.print(3.14);
    p.print(string("OOP"));

    Base *b = new Derived;
    b->show();                     // Derived version runs
    delete b;
    return 0;
}
OUTPUT
Integer: 10
Double : 3.14
String : OOP
show() of Derived

Question 5 14 marks

(a)
What is Operator overloading? Design a Distance class with data members for distance in meters, centimeters, and millimeters. Write a program to overload addition and subtraction operators respectively in a class Distance.
Unit 4: Polymorphism7 marksAsked only in this paper
ANSWER

Operator overloading

Operator overloading is a compile-time polymorphism feature that gives an additional meaning to an existing C++ operator when it is used with objects of a user-defined class. The original meaning for built-in types remains unchanged. It makes code natural: d3 = d1 + d2; instead of d3 = d1.add(d2);

Syntax:

return_type operator symbol (argument list) { ... }
Distance operator+(const Distance &d);     // inside class Distance

Rules:

  1. Only existing operators can be overloaded; new operators cannot be created.
  2. At least one operand must be a user-defined type.
  3. Precedence, associativity and the number of operands cannot be changed.
  4. These operators cannot be overloaded: :: . .* ?: sizeof typeid.
  5. A binary operator overloaded as a member function takes one argument (the left operand is the calling object); as a friend function it takes two.

Program: Distance class

To add or subtract correctly, both distances are converted to millimetres, the operation is done, and the result is converted back (1 m = 100 cm, 1 cm = 10 mm).

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

class Distance {
    int m, cm, mm;                                 // meters, centimeters, millimeters
    long toMM() const {                            // whole distance in mm
        return m * 1000L + cm * 10L + mm;
    }
    void fromMM(long total) {                      // split mm into m, cm, mm
        m = total / 1000;
        total = total % 1000;
        cm = total / 10;
        mm = total % 10;
    }
public:
    Distance(int a = 0, int b = 0, int c = 0) {
        fromMM(a * 1000L + b * 10L + c);           // normalises e.g. 120 cm
    }
    Distance operator+(const Distance &d) const {  // overloaded +
        Distance t;
        t.fromMM(toMM() + d.toMM());
        return t;
    }
    Distance operator-(const Distance &d) const {  // overloaded -
        Distance t;
        t.fromMM(toMM() - d.toMM());
        return t;
    }
    void display() const {
        cout << m << " m " << cm << " cm " << mm << " mm" << endl;
    }
};

int main() {
    Distance d1(5, 75, 8), d2(2, 40, 6);
    Distance d3 = d1 + d2;                         // d1.operator+(d2)
    Distance d4 = d1 - d2;                         // d1.operator-(d2)
    cout << "d1      = "; d1.display();
    cout << "d2      = "; d2.display();
    cout << "d1 + d2 = "; d3.display();
    cout << "d1 - d2 = "; d4.display();
    return 0;
}
OUTPUT
d1      = 5 m 75 cm 8 mm
d2      = 2 m 40 cm 6 mm
d1 + d2 = 8 m 16 cm 4 mm
d1 - d2 = 3 m 35 cm 2 mm

Explanation: d1 + d2 is translated by the compiler to d1.operator+(d2). 5758 mm + 2406 mm = 8164 mm = 8 m 16 cm 4 mm, and 5758 mm - 2406 mm = 3352 mm = 3 m 35 cm 2 mm. The program assumes the first distance is not smaller than the second when subtracting.

(b)
What is String? Explain functions of strings with suitable examples.
Unit 5: Strings, Exceptions, Threads & Collections7 marksAlso asked in Dec 2023
ANSWER

String

A string is a sequence of characters treated as a single data item, such as a name or a sentence. C++ supports strings in two ways:

1. C-style string (character array) - an array of char terminated by the null character '\0'. Functions are declared in <cstring>.

char name[20] = "Rahul";        // stored as R a h u l \0

2. C++ string class - a class in header <string>. It is an object that manages its own memory, grows automatically and supports operators such as +, =, ==, <, << and >>. This is the object-oriented way of string handling.

string city = "Bhopal";

C-style string functions (<cstring>)

Function Work Example
strlen(s) Length of string (without '\0'). strlen("OOP") → 3
strcpy(d, s) Copies s into d. strcpy(a, "Hi")
strcat(d, s) Appends s at the end of d. "Object" + "Oriented"
strcmp(a, b) Compares; returns 0 if equal, negative or positive otherwise. strcmp("abc","abd") < 0
strchr(s, c) / strstr(s, t) Finds a character / substring. strstr("C++ OOP","OOP")

Member functions of the C++ string class

Function Work
length() / size() Number of characters.
+, append() Concatenation.
insert(pos, str) Inserts a string at a position.
erase(pos, n) Removes n characters from a position.
replace(pos, n, str) Replaces n characters with another string.
find(str) / rfind(str) Position of first / last occurrence (or string::npos).
substr(pos, n) Returns a part of the string.
compare(str) / ==, < Compares two strings.
at(i) / [i] Character at a position (at() checks range).
empty(), clear(), swap() Check empty, remove all, exchange contents.
c_str() Gives the equivalent C-style string.
getline(cin, s) Reads a full line including spaces.

String handling in OOP

In OOP the string class is a good example of encapsulation and abstraction: the character array and memory management are hidden inside the object, and the user works through member functions. Operator overloading (+, ==, <<) lets strings be used like built-in types, and strings are safer than character arrays because they grow automatically and avoid buffer overflow.

Program

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

int main() {
    // ---- C-style strings (character arrays) ----
    char c1[30] = "Object", c2[] = "Oriented";
    cout << "strlen(c1)  = " << strlen(c1) << endl;
    strcat(c1, c2);
    cout << "strcat()    = " << c1 << endl;
    cout << "strcmp()    = " << (strcmp("abc", "abd") < 0 ? "negative (abc < abd)" : "not negative") << endl;

    // ---- C++ string class ----
    string s1 = "Object", s2 = "Programming";
    string s3 = s1 + " Oriented " + s2;              // + joins strings
    cout << "s3          = " << s3 << endl;
    cout << "length()    = " << s3.length() << endl;
    cout << "substr(7,8) = " << s3.substr(7, 8) << endl;
    cout << "find(Prog)  = " << s3.find("Prog") << endl;
    s3.replace(0, 6, "OBJECT");
    cout << "replace()   = " << s3 << endl;
    s3.insert(0, "C++ ");
    cout << "insert()    = " << s3 << endl;
    s3.erase(0, 4);
    cout << "erase()     = " << s3 << endl;
    cout << "s3[0], at(1)= " << s3[0] << ", " << s3.at(1) << endl;
    cout << "compare()   = " << (s1.compare(s2) < 0 ? "s1 comes before s2" : "s1 does not come first") << endl;
    return 0;
}
OUTPUT
strlen(c1)  = 6
strcat()    = ObjectOriented
strcmp()    = negative (abc < abd)
s3          = Object Oriented Programming
length()    = 27
substr(7,8) = Oriented
find(Prog)  = 16
replace()   = OBJECT Oriented Programming
insert()    = C++ OBJECT Oriented Programming
erase()     = OBJECT Oriented Programming
s3[0], at(1)= O, B
compare()   = s1 comes before s2

Question 6 14 marks

(a)
When does ambiguity arise in multiple inheritance? How can one resolve it? Develop a program in C++ to create a derived class having the following items: name, age, rollno, marks, empcode and designation. Design a base class student having data members as rollno, marks and another base class is employee having data members as empcode and designation. These both base classes are inherited from a single base class person with data members name and age. The program should carry out the required input() and output() member function for all.
Unit 3: Inheritance & Relationships7 marksAlso asked in Jun 2023
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.

Program

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

class Person {
protected:
    string name;
    int age;
public:
    void input()  { cout << "Enter name and age: "; cin >> name >> age; }
    void output() { cout << "Name: " << name << ", Age: " << age << endl; }
};

class Student : virtual public Person {            // virtual base class
protected:
    int rollno;
    float marks;
public:
    void input()  { cout << "Enter roll no and marks: "; cin >> rollno >> marks; }
    void output() { cout << "Roll No: " << rollno << ", Marks: " << marks << endl; }
};

class Employee : virtual public Person {           // virtual base class
protected:
    int empcode;
    string designation;
public:
    void input()  { cout << "Enter emp code and designation: "; cin >> empcode >> designation; }
    void output() { cout << "Emp Code: " << empcode << ", Designation: " << designation << endl; }
};

class WorkingStudent : public Student, public Employee {
public:
    void input() {                  // own input() removes name ambiguity
        Person::input();            // only ONE copy of Person exists
        Student::input();
        Employee::input();
    }
    void output() {
        cout << "--- Working Student Details ---" << endl;
        Person::output();
        Student::output();
        Employee::output();
    }
};

int main() {
    WorkingStudent ws;
    ws.input();
    ws.output();
    return 0;
}
OUTPUT
Enter name and age: Rohit 21
Enter roll no and marks: 45 82.5
Enter emp code and designation: 7001 Intern
--- Working Student Details ---
Name: Rohit, Age: 21
Roll No: 45, Marks: 82.5
Emp Code: 7001, Designation: Intern

Explanation: Student and Employee inherit Person as a virtual base class, so WorkingStudent contains only one name and age. The names input() and output() exist in three base classes; the derived class overrides them and calls each version with the scope resolution operator, removing both kinds of ambiguity. Without the keyword virtual, the statement Person::input() would give the error "Person is an ambiguous base of WorkingStudent".

(b)
Explain the concept of interfaces and abstract class in detail.
Unit 3: Inheritance & Relationships7 marksAlso asked in Dec 2023, Dec 2024, Dec 2025
ANSWER

Interface

An interface is a contract that specifies what operations a class must provide, without saying how they are implemented. It contains only method declarations (and constants), no data and no method bodies. A class that implements an interface must define all its methods.

  • Java and C# have the keyword interface (class Circle implements Drawable).
  • C++ has no interface keyword; an interface is created as a class that contains only pure virtual functions (and a virtual destructor).
class Drawable {                         // interface in C++
public:
    virtual void draw() = 0;
    virtual ~Drawable() {}
};

Abstract class

An abstract class is a class that cannot be instantiated and has at least one pure virtual (abstract) function. Unlike an interface, it can also have data members, constructors and fully defined functions, so it provides a partial implementation that derived classes complete (see the answer on abstract class).

Interface vs abstract class

Basis Interface Abstract class
Purpose Defines a contract - what to do. Gives a common base - what and partly how.
Methods Only pure virtual / abstract methods. Both abstract and concrete (defined) methods.
Data members No data members (only constants). Can have data members.
Constructor No constructor. Can have constructors.
Inheritance A class can implement many interfaces. A class (in Java) extends only one abstract class.
Relationship "can-do" (capability). "is-a" (family of classes).
Adding a method later Every implementing class must be changed. A defined method can be added without changing derived classes.
C++ form Class with only pure virtual functions. Class with at least one pure virtual function plus other members.
Example Printable, Comparable, Drawable Shape, Employee, Document

Role / use in software design and development

  1. Separation of interface from implementation - users depend on what an object does, not how; implementations can be changed freely.
  2. Loose coupling - modules communicate through interfaces, so one module can be replaced without changing others (e.g. different payment gateways).
  3. Polymorphism - one base pointer works with many implementations (see the answer on interfaces & polymorphism (code)).
  4. Extensibility (open-closed principle) - new classes can be added that implement the interface without modifying existing code.
  5. Code reuse - abstract classes keep common data and code in one place for all derived classes.
  6. Team development and testing - teams agree on interfaces first and work in parallel; mock objects implementing the interface make testing easy.
  7. Multiple inheritance of behaviour - a class can implement several interfaces safely.

When to use which: use an abstract class when related classes share common code and state (Shape → Circle, Square); use an interface when unrelated classes must provide the same capability (a Report and an Image are both Printable).

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

class Printable {                    // INTERFACE: only pure virtual functions
public:
    virtual void print() = 0;
    virtual ~Printable() {}
};

class Document {                     // ABSTRACT CLASS: data + some code
protected:
    string title;
public:
    Document(string t) { title = t; }
    virtual int pages() = 0;         // abstract part
    void info() {                    // concrete part
        cout << title << " has " << pages() << " pages" << endl;
    }
    virtual ~Document() {}
};

class Report : public Document, public Printable {
public:
    Report(string t) : Document(t) {}
    int pages() { return 12; }
    void print() { cout << "Printing report: " << title << endl; }
};

int main() {
    Report r("Annual Report");
    r.info();
    Printable *p = &r;               // used through the interface
    p->print();
    return 0;
}
OUTPUT
Annual Report has 12 pages
Printing report: Annual Report

Question 7 14 marks

(a)
Explain exception handling and multithreading.
Unit 5: Strings, Exceptions, Threads & Collections7 marksAlso asked in Jun 2023, Dec 2023, Dec 2024, 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).

Exception handling

Exception handling is the mechanism to detect and report an exceptional condition and take corrective action, so that the program does not terminate abnormally. It separates the error-handling code from the normal code. The steps are:

  1. Find the problem (hit the exception),
  2. Inform that an error has occurred (throw the exception),
  3. Receive the error information (catch the exception),
  4. Take corrective action (handle the exception).

Keywords: try, throw, catch

  • try - a block containing statements that may generate an exception.
  • throw - used to raise (throw) an exception when an error is detected; any value or object can be thrown.
  • catch - a block that catches the thrown exception and handles it; it must immediately follow the try block. The type of its argument decides which exception it handles.
try blockStatement that causes an exceptionthrow exception objectcatch blockCatches and handlesthe exceptionexceptionRest of the program
Exception handling mechanism
try {
    ...
    if (error) throw value;        // throw an exception
    ...
}
catch (type1 arg) { ... }          // handles exceptions of type1
catch (type2 arg) { ... }          // multiple catch blocks
catch (...)       { ... }          // catch-all handler

Other features: a function may rethrow an exception with throw;; the standard library provides exception classes such as exception, runtime_error, logic_error, out_of_range, invalid_argument and bad_alloc, whose what() function returns the error message. When an exception is thrown, all local objects of the try block are destroyed (stack unwinding) before control reaches the matching catch.

Program

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

double divide(int a, int b) {
    if (b == 0)
        throw runtime_error("Division by zero");     // throw an object
    return (double)a / b;
}

int main() {
    int arr[3] = {10, 20, 30};
    int index = 5;
    try {                                            // try block
        cout << "10 / 4 = " << divide(10, 4) << endl;
        if (index >= 3)
            throw index;                             // throw an int
        cout << arr[index] << endl;                  // skipped
    }
    catch (int i) {                                  // catches int
        cout << "Error: invalid index " << i << endl;
    }
    catch (runtime_error &e) {                       // catches runtime_error
        cout << "Error: " << e.what() << endl;
    }

    try {
        cout << divide(7, 0) << endl;
    }
    catch (runtime_error &e) {
        cout << "Error: " << e.what() << endl;
    }
    catch (...) {                                    // catch-all handler
        cout << "Unknown error" << endl;
    }
    cout << "Program continues normally" << endl;
    return 0;
}
OUTPUT
10 / 4 = 2.5
Error: invalid index 5
Error: Division by zero
Program continues normally

Explanation: The first throw index; is caught by catch (int). divide(7, 0) throws a runtime_error object, which is caught by its matching handler. In both cases the program continues normally instead of crashing.

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
(b)
Define polymorphism and its types. How compile time polymorphism is different from run time polymorphism.
Unit 4: Polymorphism7 marksAlso asked in Jun 2023, 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.

Differences

Basis Compile-time polymorphism Run-time polymorphism
Also called Static / early binding Dynamic / late binding
Decision made by Compiler, at compile time Program, at run time
Achieved by Function overloading, operator overloading, templates Function overriding with virtual functions
Inheritance needed Not required Required
Function signature Same name, different parameters Same name and same parameters
Keyword No special keyword virtual (and optionally override)
Call made through Object / function name Base-class pointer or reference
Speed Faster (no lookup) Slightly slower (vtable lookup)
Flexibility Less flexible More flexible and extensible
Example add(int,int) and add(double,double) Animal *a = new Dog; a->sound();

Program illustrating both types

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

class Calculator {                        // compile-time polymorphism
public:
    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; }
};

class Animal {                            // run-time polymorphism
public:
    virtual void sound() { cout << "Animal makes a sound" << endl; }
    virtual ~Animal() {}
};
class Dog : public Animal {
public:
    void sound() { cout << "Dog barks" << endl; }
};
class Cat : public Animal {
public:
    void sound() { cout << "Cat meows" << endl; }
};

int main() {
    Calculator c;                         // call fixed by the compiler
    cout << c.add(2, 3) << " " << c.add(2.5, 1.5) << " " << c.add(1, 2, 3) << endl;

    Animal *a;                            // call fixed at run time
    Dog d;
    Cat k;
    a = &d;  a->sound();
    a = &k;  a->sound();
    return 0;
}
OUTPUT
5 4 6
Dog barks
Cat meows

Explanation: The three add() calls are resolved by the compiler from their arguments (compile-time). The two a->sound() statements are identical, but the output differs because the actual object (Dog or Cat) is checked at run time through the virtual function mechanism.

Question 8 14 marks

Write short notes on (any two):

(i)
Virtual function
Unit 4: Polymorphism7 marks each (any two)Also asked in Dec 2023
ANSWER

Virtual function

A virtual function is a member function of a base class that is declared with the keyword virtual and is expected to be redefined (overridden) in derived classes. When it is called through a base-class pointer or reference, the function of the actual object is executed, decided at run time. Virtual functions are the C++ mechanism for run-time polymorphism (dynamic binding).

Rules for virtual functions:

  1. They must be members of a class; they cannot be static or friend functions.
  2. They are accessed through a pointer or reference of the base class to obtain run-time behaviour.
  3. The prototype in the base and derived class must be the same.
  4. A class with virtual functions should have a virtual destructor.
  5. Constructors cannot be virtual.
  6. If a derived class does not override it, the base-class version is used.
(ii)
File Handling
Unit 1: Introduction to OOP7 marks each (any two)Also asked in Jun 2023
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.
(iii)
Data collection
Unit 5: Strings, Exceptions, Threads & Collections7 marks each (any two)Also asked in Jun 2023, Dec 2024, Dec 2025
ANSWER

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).

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.

2 × 8 =

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