Chapter 3
Object Oriented Programming
TU BIT past exam questions
Past questions and answers
41 questions set from this chapter. Most repeated first.
- 2078 · 5 marks
Explain Memory Management Operators of C++ with example.
Answer
C++ provides the operators new and delete to allocate and free memory dynamically at run time from the heap (free store).
new allocates memory for an object or array and returns its address:
pointer = new data_type;
pointer = new data_type[size];
delete releases memory allocated by new:
delete pointer; // single object
delete[] pointer; // array
Example:
#include <iostream>
using namespace std;
int main() {
int *p = new int; // one integer
*p = 25;
int n = 5;
int *arr = new int[n]; // array of n integers
for (int i = 0; i < n; i++) arr[i] = i * 2;
cout << *p << endl;
for (int i = 0; i < n; i++) cout << arr[i] << " ";
delete p;
delete[] arr;
return 0;
}
Advantages over malloc()/free(): new automatically computes the size, returns the correct pointer type (no cast), can initialise the object (new int(10)), calls the constructor of a class object (and delete calls the destructor), and can be overloaded. If allocation fails, new throws bad_alloc.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Explain Call by Value and Call by Reference with appropriate example.
Answer
Call by value: the actual argument's value is copied into the formal parameter. Changes inside the function do not affect the original variable.
Call by reference: the function receives a reference (alias) to the actual argument (using &), so changes inside the function modify the original variable. No copy is made, which is efficient for large objects.
#include <iostream>
using namespace std;
void swapVal(int a, int b) { // call by value
int t = a; a = b; b = t;
}
void swapRef(int &a, int &b) { // call by reference
int t = a; a = b; b = t;
}
int main() {
int x = 10, y = 20;
swapVal(x, y);
cout << x << " " << y << endl; // 10 20 (unchanged)
swapRef(x, y);
cout << x << " " << y << endl; // 20 10 (swapped)
return 0;
}
| Call by value | Call by reference |
|---|---|
| Copy of the argument is passed | Alias of the argument is passed |
| Original unchanged | Original can be changed |
| Extra memory and copying time | No copying |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Describe types of constructors with an example.
Answer
A constructor is a special member function with the same name as the class and no return type. It is called automatically when an object is created, to initialise it.
Types of constructors
- Default constructor: takes no arguments (or all arguments have defaults).
- Parameterized constructor: takes arguments to initialise data members with given values.
- Copy constructor: initialises an object from another object of the same class; its parameter is a reference
const ClassName &. - (Also: dynamic constructor, which allocates memory with
new, and constructors can be overloaded.)
#include <iostream>
using namespace std;
class Student {
int roll;
float marks;
public:
Student() { roll = 0; marks = 0; } // default
Student(int r, float m) { roll = r; marks = m; } // parameterized
Student(const Student &s) { roll = s.roll; marks = s.marks; } // copy
void show() { cout << roll << " " << marks << endl; }
};
int main() {
Student s1; // default
Student s2(1, 85.5); // parameterized
Student s3(s2); // copy
s1.show(); s2.show(); s3.show();
return 0;
}
Output: 0 0, 1 85.5, 1 85.5.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Explain use of objects as function arguments with example
Answer
Objects of a class can be passed to functions like ordinary variables, either by value (a copy is made, so the original is unchanged), by reference (the original can be modified and no copy is made) or by pointer. This is commonly used for operating on two objects, e.g. adding two Time or Complex objects.
#include <iostream>
using namespace std;
class Time {
int hr, min;
public:
void set(int h, int m) { hr = h; min = m; }
Time add(Time t) { // object passed by value
Time r;
r.min = min + t.min;
r.hr = hr + t.hr + r.min / 60;
r.min = r.min % 60;
return r;
}
void show() { cout << hr << " hr " << min << " min" << endl; }
};
int main() {
Time t1, t2, t3;
t1.set(2, 40);
t2.set(1, 35);
t3 = t1.add(t2); // t2 is the object argument
t3.show(); // 4 hr 15 min
return 0;
}
Here t1 calls the function and t2 is passed as an argument; inside the function the argument's private members are accessible because it is of the same class. Passing by reference (Time &t) avoids copying.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
List out various type conversion techniques. Explain basic to user-defined type conversion with example.
Answer
Type conversion techniques
- Implicit conversion: done automatically by the compiler (e.g.
inttofloatinfloat f = 5;). - Explicit conversion (casting): done by the programmer, e.g.
(float)a,static_cast<float>(a). - Basic to user-defined (class) type: using a constructor.
- User-defined (class) to basic type: using a conversion (casting) operator function.
- One class type to another class type: using a constructor in the destination class or a conversion operator in the source class.
Basic to user-defined conversion
A single-argument constructor of the class converts a basic-type value into an object of that class.
#include <iostream>
using namespace std;
class Distance {
int meter, cm;
public:
Distance() { meter = cm = 0; }
Distance(float cmValue) { // basic (float) -> Distance
meter = (int)cmValue / 100;
cm = (int)cmValue % 100;
}
void show() { cout << meter << " m " << cm << " cm" << endl; }
};
int main() {
Distance d;
float len = 275;
d = len; // constructor is called implicitly
d.show(); // 2 m 75 cm
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
How late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example.
Answer
Early (static) binding vs late (dynamic) binding
| Early binding | Late binding |
|---|---|
| Function call is resolved at compile time | Function call is resolved at run time |
| Uses function/operator overloading and normal member functions | Uses virtual functions with base-class pointer/reference |
| Faster | Slightly slower (vtable lookup) |
| Gives compile-time polymorphism | Gives run-time (dynamic) polymorphism |
Achieving dynamic polymorphism: declare the base class function virtual, override it in derived classes, and call it through a base-class pointer (or reference) that points to a derived object. The version to execute is chosen by the type of the object pointed to, not the pointer type.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() { cout << "Shape" << endl; }
};
class Circle : public Shape {
public:
void draw() { cout << "Circle" << endl; }
};
class Square : public Shape {
public:
void draw() { cout << "Square" << endl; }
};
int main() {
Shape *p;
Circle c; Square s;
p = &c; p->draw(); // Circle
p = &s; p->draw(); // Square
return 0;
}
Without virtual, p->draw() would always print Shape.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Explain pure virtual functions with example.
Answer
A pure virtual function is a virtual function with no body in the base class, declared by assigning 0:
virtual return_type function_name(parameters) = 0;
A class containing at least one pure virtual function is an abstract class. Objects of it cannot be created, but pointers/references to it can be used. Every derived class must override the pure virtual function, otherwise it also becomes abstract. It is used to define an interface that derived classes must implement.
#include <iostream>
using namespace std;
class Shape { // abstract class
public:
virtual float area() = 0; // pure virtual function
};
class Rectangle : public Shape {
float l, b;
public:
Rectangle(float x, float y) { l = x; b = y; }
float area() { return l * b; }
};
class Circle : public Shape {
float r;
public:
Circle(float x) { r = x; }
float area() { return 3.14159 * r * r; }
};
int main() {
Shape *p;
Rectangle rc(4, 5);
Circle ci(2);
p = &rc; cout << p->area() << endl; // 20
p = &ci; cout << p->area() << endl; // 12.5664
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is exception handling? Explain how to handle an exception with appropriate example.
Answer
Exception handling: exceptions are run-time errors (such as division by zero, invalid input or failed memory allocation). Exception handling is the mechanism to detect them and respond in a controlled way instead of letting the program crash.
C++ uses three keywords:
- try: a block containing code that may cause an exception.
- throw: raises (throws) an exception when an error occurs.
- catch: a handler block that catches the thrown exception and handles it.
When an exception is thrown in the try block, control leaves the block and goes to the catch block whose parameter type matches the thrown value.
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
try {
if (b == 0)
throw "Division by zero!"; // throw
cout << "Result = " << a / b << endl;
}
catch (const char *msg) { // catch
cout << "Exception: " << msg << endl;
}
cout << "Program continues" << endl;
return 0;
}
For b = 0 the output is Exception: Division by zero! and the program continues. catch(...) catches any exception type, and several catch blocks can follow one try.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Write a program that writes the contents of file 1 into file 2.
Answer
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("file1.txt"); // source file
ofstream fout("file2.txt"); // destination file
if (!fin) {
cout << "Cannot open file1.txt" << endl;
return 1;
}
if (!fout) {
cout << "Cannot open file2.txt" << endl;
return 1;
}
char ch;
while (fin.get(ch)) // read character by character
fout.put(ch); // write to file 2
fin.close();
fout.close();
cout << "File copied successfully" << endl;
return 0;
}
The program opens file1.txt for reading with ifstream and file2.txt for writing with ofstream, copies every character until end of file, and closes both files.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 4+6 marks
What do we need template? Why the program terminate after the occurrence of exception? Describe the types of constructor.
Answer
Need for templates
Templates allow a single function or class definition to work with different data types (generic programming). Without them we would write the same code repeatedly for int, float, double, etc. They give code reuse, type safety and less code to maintain.
template <class T>
T maxOf(T a, T b) { return (a > b) ? a : b; }
// maxOf(3, 7) and maxOf(2.5, 1.5) both work
Why the program terminates after an exception occurs
When an exception is thrown, C++ uses the termination model: control leaves the current function and the stack is unwound while searching for a matching catch handler. If no suitable handler is found, terminate() is called, which calls abort() and ends the program. Even when handled, control does not return to the throw point; execution continues after the catch block. The program is terminated because the program cannot safely continue from the point of the error.
Types of constructors
- Default constructor: no arguments, e.g.
Student() {}. - Parameterized constructor: takes arguments to initialise members, e.g.
Student(int r) { roll = r; }. - Copy constructor: creates an object as a copy of another, e.g.
Student(const Student &s). - Overloaded constructors: several constructors with different parameter lists.
- Dynamic constructor: allocates memory with
newat object creation.
class Student {
int roll;
public:
Student() { roll = 0; }
Student(int r) { roll = r; }
Student(const Student &s) { roll = s.roll; }
};
Student a, b(5), c(b);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Can we use object oriented concept using structure instead of classes? Justify your opinion.
Answer
Yes. In C++ a struct is almost identical to a class: it can contain data members and member functions, constructors and destructors, access specifiers, inheritance and virtual functions. The only difference is the default access: members of a struct are public by default (and inheritance is public by default), while members of a class are private by default.
So all object-oriented concepts (encapsulation, data hiding, inheritance, polymorphism) can be achieved with a structure by using private: explicitly.
#include <iostream>
using namespace std;
struct Account {
private:
double balance; // data hiding
public:
Account(double b = 0) { balance = b; }
void deposit(double x) { balance += x; }
double get() { return balance; }
};
struct Savings : Account { // inheritance
Savings(double b) : Account(b) {}
};
int main() {
Savings s(1000);
s.deposit(500);
cout << s.get() << endl; // 1500
return 0;
}
(In C, however, structures can hold only data and have no member functions or access control, so OOP cannot be done there.) By convention struct is used for simple data aggregates and class for full objects.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
In which case default argument is used? Describe with an example.
Answer
A default argument is a value given in the function declaration that the compiler uses automatically when the caller omits that argument. It is used when a function is usually called with the same value for some parameter, or when some parameters are optional, which avoids writing overloaded versions.
Rules: default values are assigned from right to left; once a parameter has a default, all parameters to its right must also have defaults.
#include <iostream>
using namespace std;
float interest(float principal, float time = 1, float rate = 10) {
return principal * time * rate / 100;
}
int main() {
cout << interest(1000) << endl; // 100 (time=1, rate=10)
cout << interest(1000, 2) << endl; // 200 (rate=10)
cout << interest(1000, 2, 5) << endl; // 100 (no defaults used)
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
What is the task of static data members and function? Illustrate with an example.
Answer
Static data member: declared with static inside a class. Only one copy exists and it is shared by all objects of the class, instead of each object having its own. It is initialised to 0 by default, must be defined outside the class, and exists for the whole program. Task: to keep information common to all objects, such as a count of objects created.
Static member function: declared with static; it can access only static data members (and other static functions), has no this pointer, and can be called with the class name without any object: ClassName::function().
#include <iostream>
using namespace std;
class Counter {
static int count; // shared by all objects
int id;
public:
Counter() { count++; id = count; }
static void showCount() { // static member function
cout << "Objects created: " << count << endl;
}
};
int Counter::count = 0; // definition outside class
int main() {
Counter::showCount(); // 0
Counter a, b, c;
Counter::showCount(); // 3
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Differentiate between aggregation and inheritance. Why do we need virtual base class?
Answer
Aggregation vs inheritance
| Aggregation | Inheritance |
|---|---|
| "Has-a" relationship (containership) | "Is-a" relationship |
| One class contains an object of another class as a member | A derived class acquires members of a base class |
Reuse by composition, e.g. a Car has an Engine | Reuse by extension, e.g. a Dog is an Animal |
| Loose coupling; contained object is accessed through its public interface | Tighter coupling; derived class can access protected members |
| Does not give run-time polymorphism | Supports polymorphism through virtual functions |
class Engine { };
class Car { Engine e; }; // aggregation
class Animal { };
class Dog : public Animal { }; // inheritance
Need for a virtual base class
In multiple/hybrid inheritance, a class can inherit the same base class through two paths (e.g. B and C both derive from A, and D derives from B and C). Then D gets two copies of A's members, causing ambiguity and wasted memory (the diamond problem). Declaring the base as virtual makes only one shared copy of A exist in D:
class A { public: int x; };
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { }; // D has a single A::x
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Define stream. How do you read the text from file? Describe.
Answer
Stream: a stream is a sequence of bytes that flows between a program and a device (keyboard, screen, file). Input streams (istream, ifstream) carry data into the program and output streams (ostream, ofstream) carry data out. cin and cout are the standard input and output streams. File streams are provided in the <fstream> header: ifstream (read), ofstream (write) and fstream (both).
Reading text from a file
- Include
<fstream>. - Create an
ifstreamobject and open the file (in the constructor or withopen()). - Check that the file opened successfully.
- Read using
>>(word by word),get()(character) orgetline()(line), until end of file. - Close the file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream fin("data.txt"); // open file for reading
if (!fin) {
cout << "File cannot be opened" << endl;
return 1;
}
string line;
while (getline(fin, line)) // read until end of file
cout << line << endl;
fin.close();
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain the features of OOP.
Answer
Object-oriented programming (OOP) organises a program around objects that combine data and the functions that operate on it. Its main features are:
- Class and object: A class is a user-defined type (a blueprint) holding data members and member functions; an object is an instance of a class that occupies memory.
- Encapsulation: Data and functions are wrapped into a single unit (the class). Access specifiers (
private,protected,public) control visibility. - Data abstraction: Only the essential features are exposed through an interface, and implementation details are hidden. For example, a
Stackclass exposespush()andpop()without revealing its array. - Inheritance: A new (derived) class acquires the properties and behaviour of an existing (base) class, giving code reuse and hierarchical classification.
- Polymorphism: One name, many forms. Compile-time polymorphism uses function and operator overloading; run-time polymorphism uses virtual functions and overriding.
- Dynamic binding and message passing: Objects communicate by calling each other's member functions, and the function executed for a virtual call is decided at run time.
class Shape { public: virtual void draw() { cout << "Shape"; } };
class Circle : public Shape { public: void draw() { cout << "Circle"; } };
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Define namespace. List any two manipulators with their uses.
Answer
Namespace: A namespace is a named declarative region that groups identifiers (variables, functions, classes) so that names do not clash with identical names elsewhere. It is declared with the namespace keyword and accessed with the scope resolution operator or a using directive.
namespace A { int x = 10; }
namespace B { int x = 20; }
cout << A::x << B::x; // 10 20
The standard library lives in namespace std, hence using namespace std;.
Manipulators (declared in <iomanip>/<iostream>) format the stream output:
endl: inserts a newline and flushes the output buffer, e.g.cout << "Hi" << endl;setw(n): sets the field width of the next output item toncharacters (right-aligned by default), e.g.cout << setw(8) << 25;
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Why do we need friend class? How can we define member function outside the class?
Answer
Need for a friend class: Normally a class's private and protected members are accessible only to its own members. When two classes are closely related and one needs full access to the other's internals (for example, a LinkedList class and its Node class, or a controller and a data class), declaring the second as a friend class gives all its member functions access without making the data public. It avoids exposing data through many getters while keeping it hidden from the rest of the program.
class B;
class A {
int x = 5;
friend class B; // B can access A's private members
};
class B { public: void show(A a) { cout << a.x; } };
Defining a member function outside the class: declare the prototype inside the class and define it outside using the scope resolution operator ::.
class Student {
int roll;
public:
void setRoll(int r); // declaration
void display();
};
void Student::setRoll(int r) { roll = r; }
void Student::display() { cout << roll; }
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 5 marks
Explain the use of pure virtual function with example.
Answer
A pure virtual function is a virtual function with no body in the base class, declared by assigning 0:
virtual void area() = 0;
A class containing at least one pure virtual function is an abstract class; it cannot be instantiated. Every concrete derived class must override the function, otherwise it also stays abstract.
Uses:
- It defines a common interface that all derived classes must implement.
- It enables run-time polymorphism through base-class pointers or references.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void area() = 0; // pure virtual
};
class Rect : public Shape {
int l, b;
public:
Rect(int x, int y) : l(x), b(y) {}
void area() { cout << "Area = " << l * b << endl; }
};
class Circle : public Shape {
float r;
public:
Circle(float x) : r(x) {}
void area() { cout << "Area = " << 3.14159 * r * r << endl; }
};
int main() {
Shape *p;
Rect r(4, 5); Circle c(2);
p = &r; p->area(); // Area = 20
p = &c; p->area(); // Area = 12.5664
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 6+4 marks
What is constructor? Explain its types with suitable example. How is the constructor called in a derived class in C++?
Answer
Constructor: A constructor is a special member function with the same name as its class and no return type. It is called automatically when an object is created and is used to initialise the object's data members.
Types of constructors:
- Default constructor: takes no arguments.
- Parameterized constructor: takes arguments to initialise members with given values.
- Copy constructor: initialises a new object from an existing one; its parameter is a reference,
ClassName(const ClassName &obj).
#include <iostream>
using namespace std;
class Box {
int l, b;
public:
Box() { l = b = 0; } // default
Box(int x, int y) { l = x; b = y; } // parameterized
Box(const Box &o) { l = o.l; b = o.b; } // copy
void show() { cout << l << " " << b << endl; }
};
int main() {
Box b1; // default
Box b2(3, 4); // parameterized
Box b3(b2); // copy
b1.show(); b2.show(); b3.show();
}
Constructors in a derived class: The base-class constructor runs first, then the derived-class constructor. If the base class needs arguments, the derived constructor passes them using an initialiser list:
class Base {
int a;
public:
Base(int x) { a = x; cout << "Base\n"; }
};
class Derived : public Base {
int b;
public:
Derived(int x, int y) : Base(x) { b = y; cout << "Derived\n"; }
};
Creating Derived d(1, 2); prints Base then Derived. If the base has a default constructor, it is called implicitly.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
What is operator overloading? Write a complete C++ program to overload + operator to add two objects of class 'Time'.
Answer
Operator overloading is a form of compile-time polymorphism that lets an existing operator be given an additional meaning for user-defined types, using a special function named operator followed by the symbol. The precedence, associativity and number of operands of the operator do not change. Operators that cannot be overloaded include ::, ., .*, ?: and sizeof.
Program to add two Time objects using +:
#include <iostream>
using namespace std;
class Time {
int hours, minutes;
public:
Time() { hours = minutes = 0; }
Time(int h, int m) { hours = h; minutes = m; }
Time operator+(Time t) {
Time temp;
temp.minutes = minutes + t.minutes;
temp.hours = hours + t.hours + temp.minutes / 60;
temp.minutes = temp.minutes % 60;
return temp;
}
void display() {
cout << hours << " hr " << minutes << " min" << endl;
}
};
int main() {
Time t1(2, 45), t2(3, 30), t3;
t3 = t1 + t2; // t1.operator+(t2)
t1.display();
t2.display();
t3.display(); // 6 hr 15 min
return 0;
}
Here t1 + t2 is translated to t1.operator+(t2); the minutes carry over into hours when they reach 60. Output of the sum is 6 hr 15 min (2:45 + 3:30).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is the difference between public, private and protected inheritance in C++?
Answer
Inheritance mode decides how the members of the base class are seen in the derived class and outside it. Private members of the base are never directly accessible in the derived class.
| Base member | Public inheritance | Protected inheritance | Private inheritance |
|---|---|---|---|
| public | public | protected | private |
| protected | protected | protected | private |
| private | not accessible | not accessible | not accessible |
- Public inheritance models an "is-a" relationship. The public interface of the base remains public in the derived class, so outside code can call it on a derived object.
- Protected inheritance: public and protected members of the base become protected in the derived class. They can be used by the derived class and its further descendants but not by outside code.
- Private inheritance: all accessible base members become private in the derived class. They can be used only inside the derived class, and further derived classes cannot access them.
class Base { public: int a; protected: int b; };
class D1 : public Base { /* a public, b protected */ };
class D2 : protected Base { /* a protected, b protected */ };
class D3 : private Base { /* a private, b private */ };
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is exception handling? Explain types of exception handling and explain with suitable example.
Answer
Exception handling is a mechanism to detect and handle run-time errors (such as division by zero, invalid input or failed memory allocation) so that the program can recover or terminate gracefully instead of crashing. C++ provides three keywords:
try: encloses the code that may cause an exception.throw: raises an exception when an error is detected.catch: handles the exception thrown; several catch blocks may follow a try block.
Types of exceptions:
- Synchronous exceptions: arise from within the program flow, e.g. division by zero, array index out of range. These are the ones handled by try/catch.
- Asynchronous exceptions: caused by events beyond program control, such as keyboard interrupts or hardware failure; C++ exception handling is not designed for these.
Handlers can also be of different kinds: catching a specific type (catch(int)), multiple catch blocks, and a catch-all handler catch(...).
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 0;
try {
if (b == 0) throw "Division by zero";
cout << a / b;
}
catch (const char *msg) { cout << "Error: " << msg << endl; }
catch (...) { cout << "Unknown error"; }
}
Output: Error: Division by zero.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is friend function? Write a program to add private member of two different classes using friend function.
Answer
A friend function is a non-member function that is granted access to the private and protected members of a class by declaring it with the keyword friend inside the class. It is not in the scope of the class and is called like an ordinary function, with objects passed as arguments.
Program to add private members of two classes:
#include <iostream>
using namespace std;
class B; // forward declaration
class A {
int x;
public:
A(int a) { x = a; }
friend int add(A, B);
};
class B {
int y;
public:
B(int b) { y = b; }
friend int add(A, B);
};
int add(A obj1, B obj2) {
return obj1.x + obj2.y;
}
int main() {
A a(10);
B b(20);
cout << "Sum = " << add(a, b) << endl; // Sum = 30
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a program to demonstrate returning object from functions in C++.
Answer
A function can return an object by value; the return type is the class name. A copy of the object is returned to the caller.
#include <iostream>
using namespace std;
class Complex {
float re, im;
public:
Complex() { re = im = 0; }
Complex(float r, float i) { re = r; im = i; }
Complex add(Complex c) { // returns an object
Complex t;
t.re = re + c.re;
t.im = im + c.im;
return t;
}
void show() { cout << re << " + " << im << "i" << endl; }
};
int main() {
Complex c1(2, 3), c2(4, 5), c3;
c3 = c1.add(c2);
c3.show(); // 6 + 8i
return 0;
}
The function add() creates a temporary object t, fills it and returns it; the result is assigned to c3.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
How 'this' pointer is used to resolve name conflict between local variable and member variable in C++? Explain with example.
Answer
this is a hidden constant pointer available inside every non-static member function. It holds the address of the object that invoked the function. When a local variable or parameter has the same name as a data member, the local name hides the member. Writing this->member refers explicitly to the object's member, and the plain name refers to the local variable.
#include <iostream>
using namespace std;
class Student {
int roll;
float marks;
public:
void set(int roll, float marks) {
this->roll = roll; // member = parameter
this->marks = marks;
}
void show() { cout << roll << " " << marks << endl; }
};
int main() {
Student s;
s.set(5, 82.5);
s.show(); // 5 82.5
}
Without this->, the statement roll = roll; would assign the parameter to itself and leave the member unchanged. this can also be used to return the current object (return *this;) for chaining calls.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a Program to read and write values through object using File Handling.
Answer
Objects can be written to and read from a file in binary form using write() and read() of fstream.
#include <iostream>
#include <fstream>
using namespace std;
class Student {
char name[30];
int roll;
public:
void getData() {
cout << "Enter name and roll: ";
cin >> name >> roll;
}
void putData() {
cout << name << " " << roll << endl;
}
};
int main() {
Student s;
// writing
ofstream fout("student.dat", ios::binary);
s.getData();
fout.write((char*)&s, sizeof(s));
fout.close();
// reading
Student t;
ifstream fin("student.dat", ios::binary);
fin.read((char*)&t, sizeof(t));
t.putData();
fin.close();
return 0;
}
write() copies sizeof(s) bytes of the object to the file, and read() reads them back into another object.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Differentiate between function overloading and function overriding in C++.
Answer
| Function overloading | Function overriding |
|---|---|
| Several functions with the same name but different parameter lists (number, type or order) in the same scope | A derived class redefines a base-class function with the same name, same parameters and same return type |
| Does not need inheritance | Needs inheritance |
| Compile-time (static) polymorphism, resolved by the compiler | Run-time (dynamic) polymorphism when the base function is virtual |
| Return type alone cannot distinguish the functions | Signature must be identical |
Example: int add(int,int); float add(float,float); | Example: Base::show() and Derived::show() |
// overloading
int area(int s) { return s * s; }
int area(int l, int b) { return l * b; }
// overriding
class Base { public: virtual void show() { cout << "Base"; } };
class Derived : public Base { public: void show() { cout << "Derived"; } };
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Illustrate the use of static variable with a simple program.
Answer
A static data member is declared with the keyword static inside a class. Only one copy exists and it is shared by all objects of the class; it is initialised to zero by default and must be defined outside the class. A static local variable keeps its value between function calls.
#include <iostream>
using namespace std;
class Counter {
static int count; // shared by all objects
public:
Counter() { count++; }
static void show() { cout << "Objects: " << count << endl; }
};
int Counter::count = 0; // definition
void f() {
static int n = 0; // retains value between calls
n++;
cout << "Called " << n << " times" << endl;
}
int main() {
Counter a, b, c;
Counter::show(); // Objects: 3
f(); f(); // Called 1 times, Called 2 times
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 2+3+5 marks
Define stream. Explain how to read and write binary files. Write a program that reads an integer and writes it to SMALL.TXT if it is below 100, otherwise to LARGE.TXT.
Answer
Stream: A stream is a sequence of bytes that flows between a program and an input/output device (keyboard, screen, file). Input streams (istream, ifstream) supply data to the program; output streams (ostream, ofstream) carry data from the program.
Reading and writing binary files: Open the file with ios::binary mode using ifstream/ofstream/fstream. Use write((char*)&var, sizeof(var)) to write the raw bytes of a variable or object, and read((char*)&var, sizeof(var)) to read them back. Close the file with close().
ofstream fout("data.dat", ios::binary);
int n = 25;
fout.write((char*)&n, sizeof(n));
fout.close();
ifstream fin("data.dat", ios::binary);
int m;
fin.read((char*)&m, sizeof(m));
fin.close();
Program: write to SMALL.TXT if below 100, otherwise LARGE.TXT
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n;
cout << "Enter an integer: ";
cin >> n;
ofstream fout;
if (n < 100)
fout.open("SMALL.TXT", ios::app);
else
fout.open("LARGE.TXT", ios::app);
fout << n << endl;
fout.close();
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 1+3+6 marks
How does a structure differ from a class? What are the uses of friend functions and friend classes? Explain the types of constructors.
Answer
Structure vs class: In C++ both can hold data and functions. The main difference is the default access: members of a struct are public by default, while members of a class are private by default (and the default inheritance is public for struct and private for class). Classes are normally used for data hiding and OOP, structures for simple data grouping.
Uses of friend function and friend class:
- A friend function is a non-member function with access to the private and protected members of a class. It is useful for operations involving two classes (e.g. adding private members of two objects) and for overloading operators such as
<<and>>. - A friend class has all its member functions able to access the private members of another class, which is useful when two classes are tightly coupled (e.g. list and node, or manager and data class).
Types of constructors:
- Default constructor: takes no arguments, e.g.
Box() { l = 0; }. - Parameterized constructor: takes arguments to set initial values, e.g.
Box(int x) { l = x; }. - Copy constructor: creates an object as a copy of an existing one,
Box(const Box &b) { l = b.l; }. - Dynamic constructor: allocates memory with
newwhile the object is created. - Constructor with default arguments, e.g.
Box(int x = 1).
class Box {
int l;
public:
Box() { l = 0; }
Box(int x) { l = x; }
Box(const Box &b) { l = b.l; }
};
Box a, b(5), c(b);
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5+5 marks
List any two types of inheritance with examples. Describe the order of execution of constructors and destructors in a derived class.
Answer
Inheritance lets a derived class acquire the members of a base class. Two types:
- Single inheritance: one derived class from one base class.
class Animal { public: void eat() { cout << "eating"; } };
class Dog : public Animal { public: void bark() { cout << "barking"; } };
- Multilevel inheritance: a class derived from a class that is itself derived.
class A { };
class B : public A { };
class C : public B { }; // C inherits from B, which inherits from A
(Others: multiple, hierarchical and hybrid inheritance.)
Order of execution of constructors and destructors:
- Constructors run in order of derivation: the base-class constructor first, then the derived-class constructor. With multiple base classes, they run in the order in which the bases are listed in the derived class declaration; data-member objects are constructed before the derived constructor body.
- Destructors run in the reverse order: the derived-class destructor first, then the base-class destructor.
#include <iostream>
using namespace std;
class Base {
public:
Base() { cout << "Base constructor\n"; }
~Base() { cout << "Base destructor\n"; }
};
class Derived : public Base {
public:
Derived() { cout << "Derived constructor\n"; }
~Derived() { cout << "Derived destructor\n"; }
};
int main() { Derived d; }
Output:
Base constructor
Derived constructor
Derived destructor
Base destructor
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe the features of object-oriented programming.
Answer
Object-oriented programming builds programs from objects that combine data and the functions acting on it. Its features are:
- Objects and classes: A class is a blueprint defining data members and member functions. An object is a run-time instance of a class.
- Encapsulation: Binding data and functions into one unit, with access specifiers restricting direct access to the data. This provides data hiding and security.
- Abstraction: Showing only the essential interface and hiding implementation details, so users work with what an object does rather than how.
- Inheritance: A derived class reuses and extends the members of a base class. It supports reusability and hierarchical classification (single, multiple, multilevel, hierarchical, hybrid).
- Polymorphism: The ability of one name or operator to behave differently. It is achieved at compile time through function and operator overloading, and at run time through virtual functions.
- Dynamic binding: The function body executed for a call is decided at run time according to the actual object type.
- Message passing: Objects communicate by invoking each other's member functions.
Together these give modular, reusable, maintainable and extensible software.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Distinguish between concrete and abstract classes. Describe the roles of polymorphism.
Answer
Concrete vs abstract class:
| Concrete class | Abstract class |
|---|---|
| All member functions are fully defined | Contains at least one pure virtual function (virtual void f() = 0;) |
| Objects can be created | Objects cannot be created; only pointers or references can be used |
| Used directly | Used as a base class that defines a common interface |
Example: class Circle { ... } | Example: class Shape { virtual void area() = 0; } |
A derived class becomes concrete only when it overrides all pure virtual functions.
Roles of polymorphism:
- It lets one interface be used for different underlying types, so code is written once and works for many classes (e.g.
Shape*callingarea()for circles and rectangles). - Compile-time polymorphism (function and operator overloading) makes programs more readable and natural, e.g.
c1 + c2for complex numbers. - Run-time polymorphism (virtual functions) allows behaviour to be chosen according to the actual object, which makes programs extensible: new derived classes can be added without changing existing code.
- It reduces code duplication and complexity and supports the "one interface, multiple methods" principle.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Why is exception handling needed? Illustrate with an example.
Answer
Need for exception handling:
- Run-time errors (division by zero, invalid input, file not found, memory allocation failure, array index out of range) would otherwise crash the program or give wrong results.
- It separates error-handling code from the normal logic, making programs cleaner and easier to read.
- An error detected deep in a call chain can be passed up to a function that knows how to deal with it (error propagation).
- The program can recover, release resources and terminate gracefully with a meaningful message.
C++ uses try (code that may fail), throw (signals the error) and catch (handles it).
#include <iostream>
using namespace std;
double divide(int a, int b) {
if (b == 0) throw "Division by zero!";
return (double)a / b;
}
int main() {
try {
cout << divide(10, 2) << endl; // 5
cout << divide(5, 0) << endl; // throws
}
catch (const char *msg) {
cout << "Exception: " << msg << endl;
}
cout << "Program continues" << endl;
}
Output: 5, Exception: Division by zero!, Program continues.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How do you return an object from a function? Describe with an example.
Answer
A function returns an object by giving the class name as its return type and using return with an object of that class. The object is returned by value (a copy is made), or by reference/pointer if declared so.
#include <iostream>
using namespace std;
class Distance {
int feet, inches;
public:
Distance() { feet = inches = 0; }
Distance(int f, int i) { feet = f; inches = i; }
Distance add(Distance d) { // returns an object
Distance r;
r.inches = inches + d.inches;
r.feet = feet + d.feet + r.inches / 12;
r.inches %= 12;
return r;
}
void show() { cout << feet << "'" << inches << "\"" << endl; }
};
int main() {
Distance d1(5, 8), d2(3, 6), d3;
d3 = d1.add(d2);
d3.show(); // 9'2"
}
The function builds a local object r, and return r; hands a copy back to main(), where it is assigned to d3.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a program with a STUDENT class that has an age data member, and overload the unary ++ operator to increment age.
Answer
#include <iostream>
using namespace std;
class STUDENT {
int age;
public:
STUDENT(int a = 0) { age = a; }
STUDENT operator++() { // prefix ++
++age;
return *this;
}
STUDENT operator++(int) { // postfix ++
STUDENT temp = *this;
age++;
return temp;
}
void display() { cout << "Age = " << age << endl; }
};
int main() {
STUDENT s(18);
s.display(); // Age = 18
++s;
s.display(); // Age = 19
s++;
s.display(); // Age = 20
return 0;
}
The unary ++ operator is overloaded as a member function with no arguments (postfix form takes a dummy int). ++s calls s.operator++(), which increments age.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Explain the advantages and disadvantages of inline functions.
Answer
An inline function is declared with the keyword inline; the compiler is requested to replace each call with the function body, avoiding the call overhead.
inline int square(int x) { return x * x; }
Advantages:
- Removes function-call overhead (pushing arguments, jumping, returning), so small functions run faster.
- Safer than macros, since type checking is done and there are no side-effect surprises.
- Allows small accessor functions to be kept in classes without a speed penalty.
Disadvantages:
- The code is copied at every call, so the executable size increases (code bloat), especially for large functions.
- More memory use and possibly more cache misses.
- It is only a request; the compiler may ignore it for loops, recursion, static variables or large bodies.
- Any change in an inline function requires recompiling all code that uses it.
- Harder to debug.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
How do you convert a basic data type to a user-defined data type? Explain.
Answer
The compiler knows how to convert between built-in types, but not from a basic type to a user-defined class type. This is done with a constructor taking a single argument of the basic type (or by overloading the assignment operator). The constructor converts the basic value into an object when assigned or passed.
#include <iostream>
using namespace std;
class Distance {
float meters;
public:
Distance() { meters = 0; }
Distance(float cm) { // converts float -> Distance
meters = cm / 100;
}
void show() { cout << meters << " m" << endl; }
};
int main() {
Distance d;
float x = 250;
d = x; // basic type to class type, calls Distance(float)
d.show(); // 2.5 m
}
Here d = x; implicitly calls the one-argument constructor to build a temporary Distance object, which is assigned to d. (The reverse, class to basic type, needs a conversion operator function operator float().)
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Illustrate the use of setw and setprecision with examples.
Answer
Both are manipulators in <iomanip> used to format output.
setw(n) sets the field width for the next output item to n characters (right-justified by default, padded with spaces). It affects only the next item.
setprecision(n) sets the number of significant digits; combined with fixed it sets the number of digits after the decimal point.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float pi = 3.14159265;
cout << setw(10) << 25 << endl; // " 25"
cout << setprecision(3) << pi << endl; // 3.14
cout << fixed << setprecision(2) << pi << endl; // 3.14
cout << fixed << setprecision(4) << pi << endl; // 3.1416
cout << setw(8) << "Ram" << setw(6) << 90 << endl;
}
setw is commonly used to align tables in columns, and setprecision to control the decimals of floating-point values.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What are the purposes of operator overloading? How does it address the problem in multiple inheritance?
Answer
Purposes of operator overloading:
- It lets operators work with user-defined types (e.g.
c1 + c2for complex numbers,t1 + t2for times,<<for printing objects). - It makes code natural, readable and compact, close to the notation of the problem domain.
- It extends the language without changing existing operators' meaning for built-in types.
- It supports compile-time polymorphism and makes class objects behave like built-in types.
Relation to multiple inheritance: In multiple inheritance, a derived class may inherit the same member name from several bases, giving ambiguity (for example, two bases both defining operator+ or show()), and ordinary functions with different names (addA, addB) make the use of such objects cumbersome. By overloading the operator in the derived class, a single unambiguous definition is provided that combines the behaviour of both bases (e.g. the derived operator+ explicitly calls Base1::operator+ and Base2::operator+ or works with the combined data), so objects can be used with one consistent operator notation. The ambiguity can also be resolved with the scope resolution operator, e.g. obj.A::show().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BIT 2078 Second Semester Microprocessor and Computer Architecture (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Second Semester Microprocessor and Computer Architecture (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Second Semester Microprocessor and Computer Architecture (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2080.1 Second Semester Microprocessor and Computer Architecture (TU IOST semester board exam, 2080.1 (BS), via StudyNp), TU BIT 2081 Second Semester Microprocessor and Computer Architecture (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Second Semester Microprocessor and Computer Architecture (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2078 Second Semester Discrete Structure (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Second Semester Discrete Structure (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Second Semester Discrete Structure (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2080.1 Second Semester Discrete Structure (TU IOST semester board exam, 2080.1 (BS), via StudyNp), TU BIT 2081 Second Semester Discrete Structure (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2082 Second Semester Discrete Structure (TU IOST semester board exam, 2082 (BS), via StudyNp), TU BIT 2078 Second Semester Object Oriented Programming (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Second Semester Object Oriented Programming (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Second Semester Object Oriented Programming (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2081 Second Semester Object Oriented Programming (TU IOST semester board exam, 2081 (BS), via StudyNp), TU BIT 2078 Second Semester Economics (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Second Semester Economics (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Second Semester Economics (TU IOST semester board exam, 2080 (BS), via StudyNp), TU BIT 2080.1 Second Semester Economics (TU IOST semester board exam, 2080.1 (BS), via StudyNp), TU BIT 2078 Second Semester Basic Statistics (TU IOST semester board exam, 2078 (BS), via StudyNp), TU BIT 2079 Second Semester Basic Statistics (TU IOST semester board exam, 2079 (BS), via StudyNp), TU BIT 2080 Second Semester Basic Statistics (TU IOST semester board exam, 2080 (BS), via StudyNp) and TU BIT 2080.1 Second Semester Basic Statistics (TU IOST semester board exam, 2080.1 (BS), via StudyNp). Answers are written for this site; check them against your class notes.