Chapter 4
Object Oriented Programming (C++)
TU BSc CSIT past exam questions
Past questions and answers
78 questions set from this chapter, 1 of them more than once. Most repeated first.
- Asked 2 times
- 2076 · 10 marks
- 2078 · 10 marks
Write a program according to the specification given below:
- – Create a class Account with data members acc no, balance, and min_balance(static)
- -Include methods for reading and displaying values of objects
- – Define static member function to display min_balance
- -Create array of objects to store data of 5 accounts and read and display values of each object
Answer
#include <iostream>
using namespace std;
class Account {
int acc_no;
float balance;
static float min_balance; // shared by all accounts
public:
void read() {
cout << "Enter account number: ";
cin >> acc_no;
cout << "Enter balance: ";
cin >> balance;
}
void display() const {
cout << "Account No: " << acc_no
<< " Balance: " << balance << endl;
}
static void showMinBalance() { // static member function
cout << "Minimum balance: " << min_balance << endl;
}
};
float Account::min_balance = 500; // definition of static member
int main() {
Account a[5];
for (int i = 0; i < 5; i++) {
cout << "Account " << i + 1 << endl;
a[i].read();
}
Account::showMinBalance(); // called with the class name
cout << "\nAccount details\n";
for (int i = 0; i < 5; i++)
a[i].display();
return 0;
}
Explanation
min_balanceis a static data member, so one copy is shared by all five objects. It must be defined outside the class (float Account::min_balance = 500;).- A static member function can access only static members and can be called without an object, as
Account::showMinBalance(). Account a[5]creates an array of five objects, and a loop callsread()anddisplay()on each element.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 10 marks
Explain the concept of user-defined to user-defined data conversion routine located in the destination class.
Answer
Data conversion between user-defined types
C++ converts basic types automatically, but conversion between two classes (objects) must be defined by the programmer. There are two ways: a conversion operator function in the source class, or a constructor in the destination class. In the second method, the conversion routine is located in the destination class.
Idea: the destination class has a constructor that takes an object of the source class as its argument. When an object of the destination class is assigned a source object, the constructor is called automatically. It takes the source members, converts them and sets the destination's data.
Form:
class Destination {
public:
Destination(Source s) { // conversion routine
// read s's data through its public get-functions and
// compute this class's data members
}
};
Destination d = s; // or d = s; calls Destination(Source)
The destination class must be able to read the source's data, so the source class provides a public getter (or declares the destination a friend).
Example: polar to rectangular (Source = Polar, Destination = Rect)
#include <iostream>
#include <cmath>
using namespace std;
class Polar {
float r, theta; // theta in radians
public:
Polar(float r = 0, float t = 0) : r(r), theta(t) {}
float getR() const { return r; }
float getTheta() const { return theta; }
void show() const { cout << "(" << r << ", " << theta << " rad)\n"; }
};
class Rect {
float x, y;
public:
Rect(float x = 0, float y = 0) : x(x), y(y) {}
Rect(const Polar& p) { // conversion in the destination class
x = p.getR() * cos(p.getTheta());
y = p.getR() * sin(p.getTheta());
}
void show() const { cout << "(" << x << ", " << y << ")\n"; }
};
int main() {
Polar p(2.0, 0.5236); // r = 2, 30 degrees
Rect r = p; // Polar -> Rect, constructor runs
p.show();
r.show(); // about (1.73205, 1)
}
Points
- The source class needs no knowledge of the destination class.
- Using the destination-class method needs access to the source's data (getters or friend), whereas the source-class operator method needs the source to access its own data only.
- If both methods are defined for the same pair, the compiler reports an ambiguity.
- To prevent unwanted implicit conversion, the constructor can be marked
explicit.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 10 marks
Depict the difference between private and public derivation. Explain derived class constructor with suitable program.
Answer
Private and public derivation
The derivation mode (access specifier in class D : mode B) decides how the inherited members of base class B appear in derived class D.
| Base member | Public derivation | Private derivation |
|---|---|---|
| public | public in D | private in D |
| protected | protected in D | private in D |
| private | not accessible | not accessible |
- In public derivation (
class D : public B), the public interface of B remains public. An object of D can call B's public functions, so it models an "is-a" relationship. Further classes derived from D can still use B's protected members. - In private derivation (
class D : private B), all accessible members of B become private in D. Outside code cannot call B's functions through a D object, and D's own subclasses can no longer reach them. It models "implemented in terms of". - This is the default when no mode is written for a
class.
class B { public: void f(); };
class D1 : public B {};
class D2 : private B {};
D1 a; a.f(); // OK
D2 b; b.f(); // error: f() is private in D2
Derived class constructor
When a derived-class object is created, the base-class constructor runs first, then the derived-class constructor. Arguments for the base constructor are passed from the derived constructor by the initialisation list:
Derived(args) : Base(some args) { body }
If the base class has no default constructor, this is mandatory. Destructors run in the reverse order.
#include <iostream>
#include <string>
using namespace std;
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) : name(n), age(a) {
cout << "Person constructor\n";
}
};
class Student : public Person {
int roll;
float marks;
public:
Student(string n, int a, int r, float m)
: Person(n, a), roll(r), marks(m) { // base constructor first
cout << "Student constructor\n";
}
void show() {
cout << name << " " << age << " " << roll << " " << marks << endl;
}
};
int main() {
Student s("Sita", 20, 5, 82.5);
s.show();
}
Output:
Person constructor
Student constructor
Sita 20 5 82.5
Here Person(n, a) passes the values to the base class constructor, and the members roll and marks are initialised by the derived class.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 10 marks
Briefly explain the hierarchy of stream classes. Write a program that overloads extraction and insertion operators.
Answer
Hierarchy of stream classes
A stream is a flow of data between the program and a device. The C++ stream classes are arranged in this hierarchy:
ios
|
----------------
| |
istream ostream (virtual inheritance)
/ | \ / | \
istream_withassign ifstream iostream ofstream ostream_withassign
|
fstream
- ios: the base class. It holds the format flags, state flags (good, eof, fail, bad) and a pointer to the stream buffer (
streambuf). - istream: input functions (
>>,get(),getline(),read()). - ostream: output functions (
<<,put(),write()). - iostream: derived from both istream and ostream, so it supports input and output.
- istream_withassign, ostream_withassign: allow assignment of streams.
cinis an object of istream_withassign andcoutof ostream_withassign. - ifstream, ofstream, fstream: file input, file output and file input/output classes (in
<fstream>). - streambuf: provides the buffer and low-level I/O.
Overloading the extraction (>>) and insertion (<<) operators
These must be non-member (friend) functions because the left operand is a stream object, not an object of our class. They return the stream by reference so that calls can be chained.
#include <iostream>
using namespace std;
class Complex {
float re, im;
public:
Complex(float r = 0, float i = 0) : re(r), im(i) {}
friend istream& operator>>(istream& in, Complex& c);
friend ostream& operator<<(ostream& out, const Complex& c);
};
istream& operator>>(istream& in, Complex& c) {
cout << "Enter real and imaginary parts: ";
in >> c.re >> c.im;
return in;
}
ostream& operator<<(ostream& out, const Complex& c) {
out << c.re << (c.im >= 0 ? " + " : " - ")
<< (c.im >= 0 ? c.im : -c.im) << "i";
return out;
}
int main() {
Complex a, b;
cin >> a >> b;
cout << "a = " << a << "\nb = " << b << endl;
}
For input 3 4 and 5 -2, the output is a = 3 + 4i and b = 5 - 2i.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
Write a member function called reverseit() that reverses a string ( an array of character). Use a for loop that swaps the first and last characters, then the second and next-to last characters and so on. The string should be passed to reverseit() as an argument.
Answer
The function swaps the first and last characters, then the second and the second-last, and so on, up to the middle. The string is passed as an argument. Since the problem asks for a member function, it is written inside a class.
#include <iostream>
#include <cstring>
using namespace std;
class Reverser {
public:
void reverseit(char s[]) {
int n = strlen(s);
for (int i = 0; i < n / 2; i++) {
char temp = s[i];
s[i] = s[n - 1 - i];
s[n - 1 - i] = temp;
}
}
};
int main() {
char str[50];
cout << "Enter a string: ";
cin.getline(str, 50);
Reverser r;
r.reverseit(str);
cout << "Reversed: " << str << endl;
return 0;
}
For "HELLO" (n = 5), the loop runs for i = 0 and 1: swap H/O giving OELLH, then E/L giving OLLEH. The middle character is left as it is. The output is OLLEH.
Arrays are passed by address, so the change made inside reverseit() appears in the caller's string.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
What is the principle reason for using default arguments in the function? Explain how missing arguments and default arguments are handled by the function simultaneously?
Answer
Principal reason for default arguments
A default argument is a value given in the function declaration that the compiler uses automatically when the caller leaves out that argument. The main reason is convenience and simplicity: one function can serve both common and special cases, so we avoid writing several overloaded versions and long argument lists. Values that are almost always the same (such as a width, a rate or a fill character) are given once, and the caller supplies only the unusual ones.
void display(char ch = '*', int n = 10); // defaults in the declaration
Missing and default arguments handled together
When a call has fewer arguments than parameters, the supplied arguments are matched with the parameters from left to right, and the missing ones from the right end take their default values. Hence:
- The default parameters must be the rightmost ones. Once a parameter has a default, all the parameters to its right must also have defaults.
- A missing argument cannot be skipped in the middle: to set the third argument, the first two must be given.
- Defaults are specified once, in the declaration (prototype), not repeated in the definition.
#include <iostream>
using namespace std;
float volume(float l, float w = 1, float h = 1) {
return l * w * h;
}
int main() {
cout << volume(5) << endl; // 5*1*1 = 5 (w and h default)
cout << volume(5, 4) << endl; // 5*4*1 = 20 (h default)
cout << volume(5, 4, 3) << endl; // 5*4*3 = 60 (no defaults)
}
volume(5) binds l = 5 and uses the defaults for w and h. volume(5, 4) binds l and w and defaults only h. This is how missing arguments are filled by defaults in the same call.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
“An overloaded function appears to perform different activities depending the kind of data send to it” Justify the statement with appropriate example.
Answer
Justification
Function overloading means using the same function name for several functions that differ in the number or types of their parameters. When the function is called, the compiler examines the data sent (argument types and count) and calls the matching version (compile-time polymorphism). To the caller, one name area() or print() seems to do different jobs depending on the data passed, though each job is in a separate function. This makes the program easier to read and remember, since one operation is named once, not printInt, printFloat and so on.
#include <iostream>
using namespace std;
int area(int side) { return side * side; } // square
int area(int l, int b) { return l * b; } // rectangle
float area(float r) { return 3.14159f * r * r; } // circle
void show(int x) { cout << "int: " << x << endl; }
void show(double x) { cout << "double: " << x << endl; }
void show(const char* s) { cout << "string: " << s << endl; }
int main() {
cout << area(4) << endl; // 16 square
cout << area(4, 5) << endl; // 20 rectangle
cout << area(2.0f) << endl; // 12.5664 circle
show(10); // int: 10
show(2.5); // double: 2.5
show("Nepal"); // string: Nepal
}
The same name area computes a different thing for different arguments: one int gives a square, two ints a rectangle, and a float a circle. Likewise show prints each type in its own way. This supports the statement. Note that the return type alone cannot distinguish overloaded functions.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
Explain the default action of the copy constructor. Write a suitable program that demonstrates the technique of overloading the copy constructor.
Answer
Default action of the copy constructor
A copy constructor has the form ClassName(const ClassName&). It is called when an object is created from another object of the same class, when an object is passed or returned by value, and in A b = a; or A b(a);. If we do not define one, the compiler supplies a default copy constructor that does a member-wise (shallow) copy: each data member is copied one by one to the new object. This is fine for ordinary values, but when a member is a pointer, only the address is copied, so both objects point to the same memory. Changing one changes the other, and when both are destroyed the memory is freed twice (a dangling pointer or double delete error).
Programmer-defined copy constructor (deep copy)
We write our own copy constructor to allocate new memory and copy the contents.
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
char* str;
public:
MyString(const char* s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}
MyString(const MyString& other) { // copy constructor
str = new char[strlen(other.str) + 1]; // own memory
strcpy(str, other.str);
cout << "Copy constructor called\n";
}
void change(char c) { str[0] = c; }
void show() const { cout << str << endl; }
~MyString() { delete[] str; }
};
int main() {
MyString a("Hello");
MyString b = a; // copy constructor
b.change('J');
a.show(); // Hello (a is unchanged)
b.show(); // Jello
}
With the default shallow copy, a.show() would also print "Jello" and the destructors would free the same block twice. With our copy constructor each object has its own copy, so they are independent.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
Briefly explain types of inheritance used in object oriented Programming.
Answer
Inheritance is the process of creating a new (derived) class from an existing (base) class so that it reuses and extends the base's members. It supports code reuse and an "is-a" hierarchy. The types are:
1. Single inheritance: one derived class has one base class.
A -> B, written as class B : public A {};
2. Multiple inheritance: one derived class has two or more base classes.
A, B -> C, written as class C : public A, public B {};
It can cause ambiguity if both bases have a member of the same name, which is resolved with the scope resolution operator.
3. Multilevel inheritance: a class is derived from a class that is itself derived from another, forming a chain.
A -> B -> C, with class B : public A {}; class C : public B {};
4. Hierarchical inheritance: several classes are derived from one base class.
A -> B, A -> C, A -> D
5. Hybrid inheritance: a combination of two or more of the above, for example multiple and hierarchical together. It can create the "diamond problem", in which the grandchild receives two copies of the top base. It is solved with virtual base classes (class B : virtual public A).
Example of single inheritance:
class Shape { public: int w, h; };
class Rectangle : public Shape { public: int area() { return w * h; } };
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
Create a real scenario where static data members are useful. Explain with suitable example.
Answer
Static data members
A static data member is declared with the keyword static inside a class. It is shared by all objects of the class: only one copy exists in memory, no matter how many objects are made. It is initialised to zero by default, must be defined outside the class (int Class::member = value;), and exists even if no object has been created. It can be accessed as ClassName::member.
Real scenario
A bank issues account numbers and also wants to know how many accounts are open. A common counter is needed that every account object can see and update, so the data does not belong to a single object. Another example is an ID generator for students. A static member serves as the counter and also generates unique IDs.
#include <iostream>
using namespace std;
class Account {
int accNo;
double balance;
static int count; // shared by all accounts
public:
Account(double b = 0) {
balance = b;
accNo = 1000 + (++count); // unique number
}
~Account() { count--; }
void show() const {
cout << "Account " << accNo << " Rs " << balance << endl;
}
static int totalAccounts() { return count; } // static member function
};
int Account::count = 0; // definition and initialisation
int main() {
Account a(5000), b(12000);
a.show(); // Account 1001 Rs 5000
b.show(); // Account 1002 Rs 12000
cout << "Open accounts: " << Account::totalAccounts() << endl; // 2
}
Here the single variable count is shared by a and b, so each new object gets the next number and the total is kept without using a global variable.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
Create a function called swaps() that interchanges the values of the two arguments sent to it (pass these arguments by reference). Make the function into a template, so it can be used with all numerical data types (char, int, float, and so on). Write a main() program to exercise the function with several types.
Answer
A function template defines one function for all data types. The compiler generates the right version for each type used. Because the arguments are references, the originals in the caller are changed.
#include <iostream>
using namespace std;
template <class T>
void swaps(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
int i1 = 10, i2 = 20;
char c1 = 'A', c2 = 'Z';
float f1 = 1.5f, f2 = 9.75f;
double d1 = 3.14159, d2 = 2.71828;
long l1 = 100000L, l2 = 200000L;
swaps(i1, i2);
swaps(c1, c2);
swaps(f1, f2);
swaps(d1, d2);
swaps(l1, l2);
cout << "int: " << i1 << " " << i2 << endl; // 20 10
cout << "char: " << c1 << " " << c2 << endl; // Z A
cout << "float: " << f1 << " " << f2 << endl; // 9.75 1.5
cout << "double: " << d1 << " " << d2 << endl; // 2.71828 3.14159
cout << "long: " << l1 << " " << l2 << endl; // 200000 100000
return 0;
}
Both arguments must be of the same type so that T can be deduced. The compiler creates one swaps for each of int, char, float, double and long.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
Explain how exceptions are used for handling C++ error in a systematic and OOP-oriented way with the design that includes multiple exceptions.
Answer
Exception handling
An exception is a run-time error such as division by zero, an invalid index or an allocation failure. Instead of testing return codes at every call, C++ separates the error handling from normal code using three keywords:
- try: a block containing code that may cause an exception.
- throw: signals the error by throwing an object (of any type).
- catch: a handler that receives the thrown object and deals with it.
When throw runs, the control leaves the try block (the stack is unwound and local objects are destroyed), and goes to the first catch whose parameter type matches the thrown object. If none match the program terminates, unless catch(...) is used.
OOP-oriented design with multiple exceptions
A systematic design makes each kind of error its own class, so the type tells what went wrong and the object carries details (an error code, a message, the offending value). Several catch blocks follow one try block, one per exception class. They are checked in order, so specific classes are placed before general ones.
#include <iostream>
#include <string>
using namespace std;
class StackError { // base class for stack errors
protected:
string msg;
public:
StackError(string m) : msg(m) {}
virtual void show() const { cout << "Error: " << msg << endl; }
};
class Overflow : public StackError {
public: Overflow() : StackError("Stack overflow") {}
};
class Underflow : public StackError {
public: Underflow() : StackError("Stack underflow") {}
};
class Stack {
int a[3], top;
public:
Stack() : top(-1) {}
void push(int x) {
if (top == 2) throw Overflow();
a[++top] = x;
}
int pop() {
if (top == -1) throw Underflow();
return a[top--];
}
};
int main() {
Stack s;
try {
s.push(1); s.push(2); s.push(3);
s.push(4); // causes overflow
}
catch (Overflow& e) { cout << "Caught overflow: "; e.show(); }
catch (Underflow& e) { cout << "Caught underflow: "; e.show(); }
catch (...) { cout << "Unknown error\n"; }
try {
for (int i = 0; i < 4; i++) cout << s.pop() << " ";
}
catch (StackError& e) { cout << "\nCaught: "; e.show(); } // underflow
}
Output:
Caught overflow: Error: Stack overflow
3 2 1
Caught: Error: Stack underflow
Advantages: error handling is separated from normal logic; the error travels up to a caller that can deal with it; exception objects carry information; and class hierarchies let one handler catch a whole family (StackError&), while specific handlers deal with particular cases.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2075 · 5 marks
How is character I/O different from Binary I/O? Explain with examples.
Answer
Character I/O vs binary I/O
A file in C++ can be opened in text (character) mode or in binary mode (ios::binary). The two differ in how data is converted between memory and the file.
| Basis | Character (text) I/O | Binary I/O |
|---|---|---|
| Storage | Data is stored as human-readable characters (ASCII). The int 12345 is stored as the 5 characters '1'..'5'. | Data is stored exactly as the in-memory bytes. The int 12345 takes sizeof(int) = 4 bytes. |
| Functions | <<, >>, get(), put(), getline() | read(), write() |
| Conversion | Numbers are converted to and from text, so it is slower. | No conversion, so it is faster. |
| Newline | \n may be translated to \r\n (platform dependent). | No translation at all. |
| Size | Usually larger for numbers. | Compact and fixed per object. |
| Readability | Can be opened in any editor. | Unreadable in an editor. |
| Use | Notes, logs, configuration. | Records, objects, images. |
Example of character I/O
#include <fstream>
using namespace std;
int main() {
ofstream out("text.txt");
int n = 12345;
out << "Roll: " << n << endl; // written as characters
out.close();
ifstream in("text.txt");
char ch;
while (in.get(ch)) cout << ch; // read one character at a time
}
Example of binary I/O
#include <fstream>
#include <iostream>
using namespace std;
struct Student { int roll; float marks; };
int main() {
Student s = {1, 85.5f};
ofstream out("stud.dat", ios::binary);
out.write((char*)&s, sizeof(s)); // raw bytes of the object
out.close();
Student t;
ifstream in("stud.dat", ios::binary);
in.read((char*)&t, sizeof(t));
cout << t.roll << " " << t.marks;
}
The text file text.txt holds readable text, while stud.dat holds exactly sizeof(Student) bytes whatever the values are.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 10 marks
Explain the concept of operator overloading? List the operators that cannot be overloaded. Write programs to add two object of distance class with data members feet and inch by using by using member function and friend function.
Answer
Operator overloading
Operator overloading gives an existing operator an additional meaning for user-defined types (classes) while its meaning for built-in types is unchanged. It is a form of compile-time polymorphism implemented with a special function operator op. For example, + can add two Distance objects: d3 = d1 + d2;. It makes class objects behave like built-in types and makes code shorter and more readable. The number of operands, precedence and associativity of the operator cannot be changed.
Operators that cannot be overloaded
::scope resolution.member access (dot).*pointer-to-member?:conditional (ternary)sizeoftypeid(and the cast operatorsstatic_castetc.)
(a) Adding two Distance objects using a member function
#include <iostream>
using namespace std;
class Distance {
int feet, inch;
public:
Distance(int f = 0, int i = 0) : feet(f), inch(i) {}
void read() { cout << "Feet and inch: "; cin >> feet >> inch; }
void display() const { cout << feet << " ft " << inch << " in" << endl; }
Distance operator+(const Distance &d) const { // left operand is *this
Distance t;
t.inch = inch + d.inch;
t.feet = feet + d.feet + t.inch / 12;
t.inch = t.inch % 12;
return t;
}
};
int main() {
Distance d1, d2, d3;
d1.read(); d2.read();
d3 = d1 + d2; // d1.operator+(d2)
d3.display();
return 0;
}
(b) Adding two Distance objects using a friend function
#include <iostream>
using namespace std;
class Distance {
int feet, inch;
public:
Distance(int f = 0, int i = 0) : feet(f), inch(i) {}
void read() { cout << "Feet and inch: "; cin >> feet >> inch; }
void display() const { cout << feet << " ft " << inch << " in" << endl; }
friend Distance operator+(const Distance &a, const Distance &b);
};
Distance operator+(const Distance &a, const Distance &b) {
Distance t;
t.inch = a.inch + b.inch;
t.feet = a.feet + b.feet + t.inch / 12;
t.inch = t.inch % 12;
return t;
}
int main() {
Distance d1, d2, d3;
d1.read(); d2.read();
d3 = d1 + d2; // operator+(d1, d2)
d3.display();
return 0;
}
The member version takes one explicit argument (the left operand is the calling object), while the friend version takes both operands as arguments. For example, gives inches , so extra foot and in, total .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 10 marks
Explain types of polymorphism briefly. Write down roles of polymorphism. How can we achieve dynamic polymorphism briefly? Explain with example.
Answer
Polymorphism
Polymorphism means "many forms": the same name or operator behaves differently depending on context.
Types of polymorphism
- Compile-time (static, early binding) polymorphism: the call is resolved by the compiler.
- Function overloading: functions with the same name but different parameter lists.
- Operator overloading: operators given new meaning for objects.
- Run-time (dynamic, late binding) polymorphism: the call is resolved while the program runs, using virtual functions and a base-class pointer or reference.
Roles (advantages) of polymorphism
- One interface can be used for many related actions, so code is simpler and more readable.
- Code is extensible: a new derived class can be added without changing the code that uses the base class.
- Reduces the need for many differently named functions (
add,addInt,addFloat). - Allows operators to work naturally with user-defined types.
- Supports reusability and loose coupling between classes.
Achieving dynamic polymorphism
It needs: (i) inheritance, (ii) a virtual function in the base class overridden in the derived classes, and (iii) calling through a base-class pointer or reference. The compiler builds a virtual table (vtable) per class, and each object holds a hidden pointer (vptr) to it. At run time the function of the object actually pointed to is called.
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() { cout << "Drawing a shape" << endl; }
virtual ~Shape() {}
};
class Circle : public Shape {
public:
void draw() override { cout << "Drawing a circle" << endl; }
};
class Rectangle : public Shape {
public:
void draw() override { cout << "Drawing a rectangle" << endl; }
};
int main() {
Shape *p;
Circle c; Rectangle r;
p = &c; p->draw(); // Drawing a circle
p = &r; p->draw(); // Drawing a rectangle
return 0;
}
The same statement p->draw() calls different functions depending on the object p points to. Without virtual, Shape::draw() would be called both times (early binding).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
How object oriented programming differs from object based programming language? Discuss benefits of OOP.
Answer
Object-oriented vs object-based languages
An object-based language supports objects and encapsulation (data hiding) but does not support all the OOP features, mainly inheritance and (usually) polymorphism. Examples: Ada, early Visual Basic, JavaScript (prototype based). An object-oriented language supports all the main features: objects/classes, encapsulation, abstraction, inheritance and polymorphism. Examples: C++, Java, C#, Python.
| Object-based | Object-oriented |
|---|---|
| Supports objects and encapsulation. | Supports encapsulation, inheritance, polymorphism and abstraction. |
| No (or limited) inheritance. | Inheritance is a core feature. |
| Limited code reuse. | Strong code reuse through inheritance. |
| Dynamic binding usually absent. | Dynamic binding through virtual functions. |
Benefits of OOP
- Reusability: classes can be reused through inheritance, reducing development time.
- Data hiding: data is protected from accidental modification, so programs are more secure.
- Modularity: a problem is divided into independent objects, which makes development and maintenance easier.
- Natural modelling: real-world entities map directly to objects.
- Extensibility: new features are added by new classes without disturbing existing code.
- Easy maintenance and upgrade: changes are localized in classes.
- Polymorphism: one interface for many actions.
- Large programs can be handled by teams working on separate classes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
What is the use of new and delete operators? Illustrate with example. What are advantages of new malloc.
Answer
new and delete operators
new allocates memory for an object or array at run time from the free store (heap) and returns its address. delete releases memory that was obtained with new, so it can be reused (delete[] for arrays).
#include <iostream>
using namespace std;
int main() {
int *p = new int; // single int
*p = 25;
cout << *p << endl;
delete p;
int n = 4;
float *a = new float[n]; // array of n floats
for (int i = 0; i < n; i++) a[i] = i * 1.5f;
for (int i = 0; i < n; i++) cout << a[i] << " ";
delete[] a; // release the array
return 0;
}
For a class, Student *s = new Student(1, "Ram"); allocates the object and calls its constructor. delete s; calls its destructor and frees the memory.
Advantages of new over malloc
newautomatically computes the size, whilemalloc(sizeof(int)*n)needs the size given manually.newreturns the correct pointer type, whilemallocreturnsvoid*which needs a cast in C++.newcalls the constructor of the object, anddeletecalls the destructor;mallocandfreedo not.newcan be overloaded and can initialise memory (new int(10)).- On failure
newthrowsbad_alloc, whilemallocreturnsNULLthat must be checked. newis an operator, so no header file is required.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
What is destructor? Write a program to show the destructor call such that it prints the message “memory is released”.
Answer
Destructor
A destructor is a special member function that is called automatically when an object is destroyed (goes out of scope or is deleted). It is used to release resources such as dynamic memory, files or connections that the object acquired. Its name is the class name preceded by a tilde (~). It has no return type and no arguments, so it cannot be overloaded, and a class has only one destructor.
#include <iostream>
using namespace std;
class Demo {
int *p;
public:
Demo() {
p = new int[10];
cout << "Memory is allocated" << endl;
}
~Demo() {
delete[] p;
cout << "memory is released" << endl;
}
};
int main() {
cout << "Start of main" << endl;
{
Demo d; // constructor called
} // d goes out of scope, destructor called
cout << "End of main" << endl;
return 0;
}
Output:
Start of main
Memory is allocated
memory is released
End of main
Objects are destroyed in the reverse order of their creation.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
What is this pointer? How can we use it for name conflict resolution? Illustrate with example.
Answer
this pointer
this is a hidden constant pointer available inside every non-static member function. It holds the address of the object that invoked the function, so *this is the calling object itself. The compiler passes it implicitly as an extra argument.
Uses
- Resolving name conflict between a data member and a parameter or local variable of the same name.
- Returning the current object (
return *this;) to chain function calls. - Passing the current object's address to another function.
Name conflict resolution
When a parameter has the same name as a data member, the local name hides the member. this->name refers to the member explicitly.
#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(7, 82.5);
s.show(); // 7 82.5
return 0;
}
Without this->, the statement roll = roll; would assign the parameter to itself and the data member would remain uninitialised.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
How can you define catch statement that can catch any type of exception? Illustrate the use of multiple catch statement with example.
Answer
Catch-all handler
A catch block with an ellipsis catch(...) catches an exception of any type. It should be placed after the specific handlers, because handlers are tried in order.
try {
throw 3.5;
}
catch (...) {
cout << "Some exception caught";
}
Multiple catch statements
A single try block may throw different types of exceptions. Several catch blocks follow it, one for each type, and the first one whose type matches is executed.
#include <iostream>
using namespace std;
void test(int x) {
try {
if (x == 0) throw 0; // int
else if (x == 1) throw 'a'; // char
else if (x == 2) throw 2.5; // double
else cout << "No exception" << endl;
}
catch (int e) { cout << "Integer exception caught" << endl; }
catch (char e) { cout << "Character exception caught" << endl; }
catch (...) { cout << "Any other exception caught" << endl; }
}
int main() {
test(0); // Integer exception caught
test(1); // Character exception caught
test(2); // Any other exception caught (double)
test(5); // No exception
return 0;
}
Only one handler runs for a given throw, and catch(...) handles the double because no specific handler matches.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2076 · 5 marks
Which functions can be used for reading and writing object? Describe briefly. Write a program that read values of two objects of student class(assume data members are sid , sname, and level) and display the data in monitor.
Answer
Functions for reading and writing objects
Objects are stored in binary files using the stream functions:
write((char*)&obj, sizeof(obj))ofofstream/fstreamwrites the raw bytes of an object to a file.read((char*)&obj, sizeof(obj))ofifstream/fstreamreads the bytes back into an object.
Both take a char* (so the object address is cast) and the number of bytes to transfer.
Program
The program reads two student objects from the keyboard, writes them to a file, reads them back and displays them on the monitor.
#include <iostream>
#include <fstream>
using namespace std;
class student {
int sid;
char sname[30];
int level;
public:
void getdata() {
cout << "Enter sid, name, level: ";
cin >> sid >> sname >> level;
}
void putdata() const {
cout << sid << "\t" << sname << "\t" << level << endl;
}
};
int main() {
student s[2], t;
ofstream out("student.dat", ios::binary);
for (int i = 0; i < 2; i++) {
s[i].getdata();
out.write((char*)&s[i], sizeof(s[i]));
}
out.close();
ifstream in("student.dat", ios::binary);
cout << "SID\tName\tLevel" << endl;
while (in.read((char*)&t, sizeof(t)))
t.putdata();
in.close();
return 0;
}
A character array is used for the name (not string) so that the object contains no pointers and can be safely stored as raw bytes.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
What is meant by type conversion? Define two way of converting one user defined data type (object) to another user defined object? Write a program that converts object of another distance class with data members feet and inch.(Assume 1m = 3.3 feet and 1cm = 0.4 inch)
Answer
Type conversion
Type conversion is the process of changing a value of one data type into another. For built-in types it is done by the compiler (implicit conversion) or by a cast (explicit conversion). For user-defined types (objects) the compiler does not know the rules, so the programmer must specify them.
Two ways of converting one object type to another
- Conversion function (casting operator) in the source class. A member function
operator DestType()of the source class returns an object of the destination type. It has no return type in its declaration and no arguments.Source s; Dest d = s;callss.operator Dest(). - One-argument constructor in the destination class. A constructor
Dest(Source s)builds a destination object from a source object.Dest d = s;callsDest(s).
Rule: use a conversion function when the source class is to be changed, and a constructor when the destination class is to be changed. Both must not be defined for the same conversion, otherwise the call is ambiguous.
Program: metric distance (m, cm) to feet-inch distance
Given: and . The program defines class Metric (metre, centimetre) and class Distance (feet, inch), and converts a Metric object into a Distance object with a conversion function.
#include <iostream>
using namespace std;
class Distance {
float feet, inch;
public:
Distance(float f = 0, float i = 0) : feet(f), inch(i) {}
void display() const { cout << feet << " feet " << inch << " inch" << endl; }
};
class Metric {
float m, cm;
public:
void read() { cout << "Enter metre and centimetre: "; cin >> m >> cm; }
operator Distance() const { // conversion function Metric -> Distance
float f = m * 3.3;
float i = cm * 0.4;
return Distance(f, i);
}
};
int main() {
Metric a;
a.read();
Distance d = a; // a.operator Distance()
d.display();
return 0;
}
Example: for ,
so the output is 6.6 feet 4 inch.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 10 marks
How ambiguity arises in multipath inheritance? How can you remove this type of ambiguity? Explain with suitable example.
Answer
Ambiguity in multipath inheritance
Multipath inheritance (the diamond problem) occurs when a class is derived from two classes which are both derived from one common base class. Example: B and C derive from A, and D derives from both B and C.
Then D inherits two copies of every member of A (one through B, one through C). A reference such as d.a or a call d.show() (where show() is in A) is ambiguous because the compiler cannot decide which copy is meant, and memory is also wasted by the duplicate.
class A { public: int a; void show() { cout << "A: " << a << endl; } };
class B : public A {};
class C : public A {};
class D : public B, public C {};
// D d; d.a = 5; // ERROR: ambiguous, B::A::a or C::A::a ?
Removing the ambiguity
- Scope resolution operator: name the path explicitly, as
d.B::a = 5;ord.C::show();. Two copies still exist. - Virtual base class (preferred): declare the common base as
virtualin the intermediate classes. Then only one shared copy ofAexists inD.
#include <iostream>
using namespace std;
class A {
public:
int a;
void show() { cout << "a = " << a << endl; }
};
class B : virtual public A { public: int b; };
class C : virtual public A { public: int c; };
class D : public B, public C {
public:
int d;
void display() {
a = 10; // no ambiguity, single copy of a
b = 20; c = 30; d = 40;
cout << a << " " << b << " " << c << " " << d << endl;
}
};
int main() {
D obj;
obj.display(); // 10 20 30 40
obj.show(); // a = 10
return 0;
}
Because A is a virtual base, D contains a single A subobject, so obj.show() is unambiguous and memory is saved.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is structured programming? Discuss characteristics and problems associated with structured programming.
Answer
Structured programming
Structured programming is a programming approach in which a program is divided into small procedures (functions) and is built from three control structures: sequence, selection (if, switch) and iteration (for, while). It follows a top-down design, avoids unrestricted goto, and the emphasis is on the functions (procedures) that act on data. Examples: C, Pascal, FORTRAN.
Characteristics
- Top-down approach: the problem is decomposed into smaller sub-problems.
- Modularity: each task is written as a function and is reused by calling it.
- Uses only sequence, selection and iteration;
gotois avoided. - Data and functions are separate; data is passed between functions as arguments or kept global.
- Easier to read, test, debug and maintain than unstructured programs.
Problems
- Data is global or freely passed, so any function can change it. There is no data hiding, which makes programs less secure.
- A change in the data structure requires changes in all the functions that use it.
- It does not model real-world entities well, because functions and data are separate.
- Poor code reusability: extending the program often means rewriting or copying code.
- Large programs become difficult to maintain and debug, as the number of functions and their data dependencies grows.
- Adding new data types is hard, since there is no inheritance or polymorphism.
These problems are overcome by object-oriented programming, which binds data and functions in objects.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is the use of get and getline functions? Explain with suitable example.
Answer
get() and getline()
Both are member functions of the input stream istream (used with cin and with file streams). They read characters including white space, unlike the extraction operator >> which stops at the first space.
get()
cin.get(ch)reads a single character (including space, tab and newline) intoch.cin.get(str, n)reads up ton-1characters intostr, stopping at a newline. The newline is left in the input stream.
getline()
cin.getline(str, n)reads up ton-1characters or until a newline is found. The newline is extracted and discarded, and the string is terminated with'\0'.cin.getline(str, n, delim)uses a delimiter character other than newline.
Difference: get(str,n) leaves the delimiter in the stream, while getline removes it.
#include <iostream>
using namespace std;
int main() {
char ch, name[30], address[50];
cout << "Enter a character: ";
cin.get(ch); // reads one character
cin.ignore(100, '\n'); // discard rest of the line
cout << "Enter your full name: ";
cin.getline(name, 30); // reads "Ram Bahadur Thapa" with spaces
cout << "Enter address: ";
cin.getline(address, 50);
cout << ch << endl << name << endl << address << endl;
return 0;
}
If cin >> name was used, only the first word (Ram) would be read.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is meant by pass by reference? How can we pass arguments by reference by using reference variable? Illustrate with example.
Answer
Pass by reference
In pass by reference the function receives the address (an alias) of the actual argument rather than a copy, so changes made to the parameter inside the function change the original variable. It avoids copying large objects and lets a function return more than one result.
Using a reference variable
A reference variable is an alias for an existing variable, declared with &: int &r = x;. If a function parameter is declared as a reference, the argument is passed by reference without needing * and & in the call.
#include <iostream>
using namespace std;
void swap(int &a, int &b) { // a and b are aliases of the actual arguments
int t = a;
a = b;
b = t;
}
int main() {
int x = 10, y = 20;
cout << "Before: " << x << " " << y << endl;
swap(x, y); // plain call, no & needed
cout << "After: " << x << " " << y << endl;
return 0;
}
Output:
Before: 10 20
After: 20 10
Inside swap, a is another name for x and b for y, so exchanging them exchanges x and y. With pass by value, the original values would remain unchanged.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is constructor? Explain the concept of default and default copy with suitable example.
Answer
Constructor
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 and is used to initialise the data members. It can be overloaded.
Default constructor
A constructor that takes no arguments (or has defaults for all arguments). If the programmer defines no constructor, the compiler supplies an implicit default constructor which does nothing for built-in members.
class Box {
int l, b;
public:
Box() { l = 1; b = 1; } // default constructor
};
Box x; // calls Box()
Default copy constructor
A copy constructor ClassName(const ClassName &obj) initialises a new object from an existing object of the same class. If the programmer does not write one, the compiler provides a default copy constructor that copies each data member one by one (memberwise or shallow copy). It is called in Box y = x;, Box y(x);, when an object is passed or returned by value.
#include <iostream>
using namespace std;
class Box {
int l, b;
public:
Box() { l = 1; b = 1; }
Box(int a, int c) { l = a; b = c; }
void show() { cout << l << " x " << b << endl; }
};
int main() {
Box x; // default constructor: 1 x 1
Box y(4, 5); // parameterized constructor
Box z = y; // default (compiler generated) copy constructor
x.show(); y.show(); z.show(); // 1 x 1, 4 x 5, 4 x 5
return 0;
}
The default copy is adequate here, but if a class holds a pointer to dynamic memory, a shallow copy makes two objects share the same memory, so a user-defined deep-copy constructor is needed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is the concept of friend function? How it violates the data hiding principle? Justify with example.
Answer
Friend function
A friend function is a non-member function that is given permission to access the private and protected members of a class. It is declared inside the class with the keyword friend, but defined outside without the scope operator.
Characteristics:
- It is not in the scope of the class and is called like a normal function (not with an object and the dot operator).
- It must use an object name with the dot operator to access members, e.g.
a.x. - It can be declared anywhere in the class (private or public section makes no difference).
- It is used for operator overloading with a left non-class operand, and to operate on private data of two different classes.
How it violates data hiding
Data hiding says that private data can be accessed only by member functions of the class. A friend function is not a member, yet it can read and modify the private data directly, so the encapsulation boundary is broken. Hence friends must be used with care.
#include <iostream>
using namespace std;
class Account {
int balance; // private
public:
Account(int b) : balance(b) {}
friend void tamper(Account &a); // friend declaration
};
void tamper(Account &a) {
a.balance = 999999; // direct access to a private member
cout << "Balance changed to " << a.balance << endl;
}
int main() {
Account acc(500);
// cout << acc.balance; // ERROR: private
tamper(acc); // works because of friendship
return 0;
}
acc.balance cannot be touched from main, but the friend function tamper freely modifies it, which shows that friendship bypasses data hiding.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is exception? Why exception handling is better to use? Explain exception handling with try….. catch by using suitable example.
Answer
Exception
An exception is a run-time error or abnormal condition that disrupts the normal flow of a program, e.g. division by zero, failure of memory allocation, invalid array index, or file not found.
Why exception handling is better
- It separates the error-handling code from the normal code, so the program is cleaner than with many
ifchecks. - The error can be detected where it occurs but handled at a suitable higher level (propagation up the call stack).
- Different types of errors can be handled differently with multiple catch blocks.
- Unlike returning error codes, an exception cannot be ignored silently; an unhandled one terminates the program.
- Resources are cleaned up as the stack unwinds (destructors of local objects run).
try, throw, catch
tryencloses the code that may cause an exception.throwraises an exception, passing a value (the exception object).catchhandles an exception of a matching type. Control goes to the matching catch block, and then continues after the last catch block.
#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 input 10 0 the output is Exception: Division by zero! followed by Program continues. For input 10 2 the output is Result = 5.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
When class templates are useful? How can you define a class that can implement stack with integer as well as sack of strings? Illustrate with example.
Answer
Class templates
A class template defines a generic class in which one or more data types are parameters. It is useful when the same logic must work for different data types (stack, queue, linked list, array container), because it avoids writing a separate class for each type, which gives code reuse and type safety. The compiler generates the actual class when a type is supplied: Stack<int>, Stack<string>.
Generic stack
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Stack {
T arr[50];
int top;
public:
Stack() : top(-1) {}
void push(T x) {
if (top == 49) { cout << "Stack overflow" << endl; return; }
arr[++top] = x;
}
T pop() {
if (top == -1) { cout << "Stack underflow" << endl; return T(); }
return arr[top--];
}
bool empty() const { return top == -1; }
};
int main() {
Stack<int> si; // stack of integers
si.push(10); si.push(20);
cout << si.pop() << endl; // 20
cout << si.pop() << endl; // 10
Stack<string> ss; // stack of strings
ss.push("Nepal"); ss.push("Kathmandu");
cout << ss.pop() << endl; // Kathmandu
cout << ss.pop() << endl; // Nepal
return 0;
}
The single template Stack<T> is instantiated once with T = int and once with T = string, so the same code serves both kinds of stack.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
What is meant by stream? Write a program that reads content of file data.txt and displays the content in monitor.
Answer
Stream
A stream is a sequence of bytes that flows between a program and an input or output device. It is an abstraction that lets the program use the same functions for the keyboard, monitor and files. An input stream (istream, ifstream) carries data into the program, and an output stream (ostream, ofstream) carries data out of it. cin is attached to the keyboard and cout to the monitor; file streams from <fstream> are attached to disk files.
Program to display the content of data.txt
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream fin("data.txt"); // open file for reading
if (!fin) {
cout << "Cannot open data.txt" << endl;
return 1;
}
char ch;
while (fin.get(ch)) // read character by character until EOF
cout << ch; // show on monitor
fin.close();
return 0;
}
fin.get(ch) returns false at end of file, which ends the loop. Reading with >> instead would skip white space and lose the layout of the text.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2078 · 5 marks
Write short notes on:
- Manipulators
- Protected Access Specifier
Answer
Manipulators
Manipulators are special functions or objects used with the insertion (<<) and extraction (>>) operators to format input and output. They are in <iostream> (e.g. endl) and <iomanip> (those with arguments).
| Manipulator | Use |
|---|---|
endl | inserts a newline and flushes the buffer |
setw(n) | sets the field width to n |
setprecision(n) | sets the number of significant (or fixed) digits |
setfill(c) | fills unused width with character c |
fixed, scientific | floating point format |
left, right | alignment |
dec, hex, oct | number base |
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setw(8) << setfill('*') << 42 << endl; // ******42
cout << fixed << setprecision(2) << 3.14159 << endl; // 3.14
cout << hex << 255 << endl; // ff
}
Users can also define their own manipulators as functions that take and return a stream reference.
Protected access specifier
protected is an access specifier whose members are accessible within their own class and in the classes derived from it, but not by ordinary outside code (objects in main). It lies between private (class only) and public (everywhere). It is used so that a derived class can use the base class data directly while the data stays hidden from the rest of the program.
class Base {
protected:
int x; // visible to derived classes
};
class Derived : public Base {
public:
void set() { x = 10; } // allowed
};
// Derived d; d.x = 5; // error: x is protected
With public inheritance, protected members of the base remain protected in the derived class.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
What is aggregation? Write a program for implementing following:
Create a class author with attributes name and qualification. Also create a class publication with pname. From these classes derive a classes derive a class book having attributes title and price. Each of the three classes should have getdata() method to get their data from user. The classes should have putdata() method to display the data. Create instance of the class book in main.
Answer
Aggregation
Aggregation is a "has-a" (whole-part) relationship in which one class contains an object of another class as a member. The contained object can exist independently of the container (weaker than composition). Example: a Library has Book objects, a Car has an Engine. It is another way of reuse besides inheritance, and is implemented by declaring an object (or pointer) of one class inside another.
Program
book is derived from author and publication (multiple inheritance), so it reuses their data and functions.
#include <iostream>
#include <string>
using namespace std;
class author {
protected:
string name, qualification;
public:
void getdata() {
cout << "Enter author name: ";
getline(cin, name);
cout << "Enter qualification: ";
getline(cin, qualification);
}
void putdata() const {
cout << "Author: " << name << " Qualification: " << qualification << endl;
}
};
class publication {
protected:
string pname;
public:
void getdata() {
cout << "Enter publication name: ";
getline(cin, pname);
}
void putdata() const {
cout << "Publication: " << pname << endl;
}
};
class book : public author, public publication {
string title;
float price;
public:
void getdata() {
author::getdata();
publication::getdata();
cout << "Enter title: ";
getline(cin, title);
cout << "Enter price: ";
cin >> price;
}
void putdata() const {
author::putdata();
publication::putdata();
cout << "Title: " << title << " Price: Rs " << price << endl;
}
};
int main() {
book b; // instance of book
b.getdata();
cout << "\n--- Book details ---\n";
b.putdata();
return 0;
}
Since both base classes have getdata() and putdata(), the scope resolution operator (author::getdata()) removes the ambiguity inside book, and book defines its own versions that call both.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
What is operator overloading? Why it is necessary to overload an operator? Write a program for overloading comparision operator.
Answer
Operator overloading
Operator overloading is a feature of C++ that lets an existing operator be given an additional meaning for objects of a user-defined class, by writing a function named operator followed by the symbol. It is a type of compile-time polymorphism. The meaning for built-in types is unchanged, and the precedence, associativity and number of operands cannot be changed.
Why it is necessary
- To use operators on objects the way they are used on built-in types (
c = a + b;,if (a < b)), which is more natural thana.add(b)anda.isLess(b). - It makes code shorter, more readable and closer to the mathematical notation of the problem (complex numbers, vectors, distances, matrices).
- It lets user-defined types behave like built-in types, so they can be used in generic code.
Program: overloading comparison operators for a Distance class
#include <iostream>
using namespace std;
class Distance {
int feet, inch;
public:
Distance(int f = 0, int i = 0) : feet(f), inch(i) {}
void read() { cout << "Enter feet and inch: "; cin >> feet >> inch; }
int totalInches() const { return feet * 12 + inch; }
bool operator<(const Distance &d) const {
return totalInches() < d.totalInches();
}
bool operator>(const Distance &d) const {
return totalInches() > d.totalInches();
}
bool operator==(const Distance &d) const {
return totalInches() == d.totalInches();
}
};
int main() {
Distance d1, d2;
d1.read();
d2.read();
if (d1 < d2) cout << "d1 is smaller than d2" << endl;
else if (d1 > d2) cout << "d1 is greater than d2" << endl;
if (d1 == d2) cout << "d1 and d2 are equal" << endl;
return 0;
}
Example: in and in; as , the program prints d1 is greater than d2. Comparing only feet and inch separately would fail in cases like vs if inch were checked first, hence the conversion to total inches.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
What is the use of constructor and destructor? Write a program for illustrating default constructor, parameterized constructor and copy constructor.
Answer
Use of constructor
A constructor is a special member function with the same name as the class, called automatically when an object is created. It initialises the data members so that an object always starts in a valid state, may allocate resources (e.g. dynamic memory), and can be overloaded so that objects are created in different ways. It has no return type.
Use of destructor
A destructor (~ClassName()) is called automatically when an object goes out of scope or is deleted. It releases resources acquired by the object (dynamic memory, open files), performs clean-up, takes no arguments, cannot be overloaded, and objects are destroyed in reverse order of creation.
Program
#include <iostream>
#include <cstring>
using namespace std;
class Student {
int roll;
char *name;
public:
Student() { // default constructor
roll = 0;
name = new char[8];
strcpy(name, "Unknown");
cout << "Default constructor" << endl;
}
Student(int r, const char *n) { // parameterized constructor
roll = r;
name = new char[strlen(n) + 1];
strcpy(name, n);
cout << "Parameterized constructor" << endl;
}
Student(const Student &s) { // copy constructor (deep copy)
roll = s.roll;
name = new char[strlen(s.name) + 1];
strcpy(name, s.name);
cout << "Copy constructor" << endl;
}
void show() const { cout << roll << " " << name << endl; }
~Student() { // destructor
delete[] name;
cout << "Destructor for " << roll << endl;
}
};
int main() {
Student s1; // default
Student s2(2, "Sita"); // parameterized
Student s3(s2); // copy
s1.show(); s2.show(); s3.show();
return 0;
}
Output order: three constructor messages, then the three show() lines, then destructor messages for s3, s2, s1 (reverse order of creation). The copy constructor makes a separate copy of the name, so deleting s3 does not affect s2.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Describe the characteristics of object oriented programming language
Answer
Characteristics of an object-oriented programming language
Object-oriented programming (OOP) organises a program around objects that combine data and the functions operating on it, rather than around functions alone. The main characteristics are the following.
1. Objects and classes
An object is an instance of a class and represents a real-world entity with state (data members) and behaviour (member functions). A class is a user-defined data type, a blueprint from which objects are created. Example: class Student, object s1.
2. Encapsulation
Binding data and the functions that work on it into a single unit (class). Access specifiers (private, protected, public) control access, so the data is hidden from outside and can be reached only through the public interface. This gives data hiding and security.
3. Abstraction
Showing only essential features and hiding the implementation details. A user calls s.display() without knowing how it is done. In C++ it is achieved with classes and abstract classes (pure virtual functions).
4. Inheritance A new class (derived class) acquires the properties and behaviour of an existing class (base class). It supports reusability and the hierarchy "is-a". Types: single, multiple, multilevel, hierarchical, hybrid.
5. Polymorphism One name, many forms. Compile-time: function and operator overloading. Run-time: virtual functions with base-class pointers.
6. Dynamic binding The code executed for a function call is decided at run time, according to the type of the object, rather than at compile time (used with virtual functions).
7. Message passing
Objects communicate by sending messages, i.e. calling the member functions of other objects with arguments, e.g. account.deposit(500).
8. Bottom-up approach and emphasis on data Programs are built from objects upward, and data is given more importance than procedure; data is not freely accessible by all functions as in procedural programming.
These features make OOP programs modular, reusable, extensible and easier to maintain than procedural programs.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Define class and object with suitable example. How members of class can be accessed?
Answer
(a) Class. A class is a user-defined data type that binds data members (attributes) and member functions (behaviour) into a single unit. It is a blueprint; no memory is allocated for the class itself until objects are created.
Object. An object is an instance of a class. It occupies memory and has its own copy of the data members. Many objects can be created from one class.
Example:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int roll;
string name;
public:
void setData(int r, string n) {
roll = r;
name = n;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1, s2; // objects
s1.setData(1, "Ram"); // access through dot operator
s2.setData(2, "Sita");
Student *p = &s2;
s1.display();
p->display(); // access through pointer and arrow operator
return 0;
}
Output:
Roll: 1, Name: Ram
Roll: 2, Name: Sita
(b) Accessing members of a class.
- Access is controlled by the specifiers
private(default for a class; accessible only inside the class and by friends),protected(class and derived classes) andpublic(anywhere). - Dot operator with an object:
s1.display(); - Arrow operator with a pointer to an object:
p->display();(equivalent to(*p).display()). - Scope resolution operator for static members:
ClassName::staticMember. - Private data is reached indirectly through public member functions (getters and setters), which supports data hiding.
- Inside a member function, other members are accessed directly by name (or through the
thispointer).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
What is inline function? Why it is used? Write a program to illustrate inline function.
Answer
Inline function. An inline function is a function declared with the keyword inline. It is a request to the compiler to replace each call of the function with the function body at the point of the call, instead of performing a normal function call.
Why it is used.
- A normal call costs time: pushing arguments and the return address on the stack, jumping to the function and returning. Inline expansion removes this overhead.
- It makes small, frequently called functions (such as getters,
max,square) faster while keeping the readability of a function. - It is type safe, unlike a macro, because the compiler checks argument types.
- Drawback: code size grows if a large function is expanded at many call sites. The compiler may ignore the request for loops,
staticvariables, recursion or large bodies.
Program:
#include <iostream>
using namespace std;
inline int cube(int x) {
return x * x * x;
}
inline int maxOf(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int n = 4;
cout << "Cube of " << n << " = " << cube(n) << endl;
cout << "Greater of 12 and 7 = " << maxOf(12, 7) << endl;
return 0;
}
Output:
Cube of 4 = 64
Greater of 12 and 7 = 12
Each call to cube and maxOf is replaced by the code of the function at compile time.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
What are the various class access specifiers? How public inheritance differs from private inheritance?
Answer
(a) Class access specifiers. C++ provides three:
| Specifier | Accessible from |
|---|---|
private | Only member functions and friends of the same class (default in a class) |
protected | The class, its friends and its derived classes |
public | Any code that has an object of the class |
They implement data hiding and encapsulation: data is normally kept private or protected, and the interface is made public.
(b) Public versus private inheritance. The mode of inheritance decides how the base-class members are seen in the derived class.
| Base member | Public inheritance | Private inheritance |
|---|---|---|
| public | stays public in derived | becomes private in derived |
| protected | stays protected | becomes private |
| private | not accessible | not accessible |
- With public inheritance the relationship is "is-a". Objects of the derived class can use the public base interface directly (
d.baseFunc()), and a derived object can be used where a base object is expected. - With private inheritance the relationship is "implemented in terms of". The base public members are usable only inside the derived class, so outside code cannot call them through a derived object, and further classes derived from it cannot access them.
class Base { public: void show() {} };
class D1 : public Base {};
class D2 : private Base {};
D1 a; a.show(); // allowed
D2 b; b.show(); // error: show() is private in D2
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Write a program to implement function template with multiple arguments.
Answer
A function template defines a family of functions. With multiple template arguments, each type parameter is declared separately, so that parameters of different types can be handled by one definition.
#include <iostream>
using namespace std;
template <class T1, class T2>
void display(T1 a, T2 b) {
cout << "First = " << a << ", Second = " << b << endl;
}
template <class T1, class T2>
double addValues(T1 a, T2 b) {
return a + b;
}
int main() {
display(10, 3.5);
display('A', "Hello");
display(25, 'x');
cout << "Sum = " << addValues(5, 2.5) << endl;
cout << "Sum = " << addValues(1.5f, 4) << endl;
return 0;
}
Output:
First = 10, Second = 3.5
First = A, Second = Hello
First = 25, Second = x
Sum = 7.5
Sum = 5.5
The compiler deduces T1 and T2 from the arguments of each call and generates a separate function for each distinct combination of types.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Write a program to illustrate the use of seekg() and tellg().
Answer
seekg() moves the get (read) pointer of an input stream and tellg() returns its current position (in bytes from the beginning of the file).
seekg(pos)moves to an absolute position.seekg(offset, dir)moves relative toios::beg,ios::curorios::end.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// create a file
ofstream out("data.txt");
out << "HELLO WORLD";
out.close();
ifstream in("data.txt");
char ch;
cout << "Initial position: " << in.tellg() << endl; // 0
in.seekg(6); // go to 7th character
cout << "Position now: " << in.tellg() << endl; // 6
in.get(ch);
cout << "Character read: " << ch << endl; // W
in.seekg(0, ios::end); // go to end
cout << "File size: " << in.tellg() << " bytes" << endl; // 11
in.seekg(-5, ios::end); // 5 bytes before the end
in.get(ch);
cout << "Character: " << ch << endl; // W
in.seekg(0, ios::beg); // back to beginning
while (in.get(ch)) cout << ch;
cout << endl;
in.close();
return 0;
}
Output:
Initial position: 0
Position now: 6
Character read: W
File size: 11 bytes
Character: W
HELLO WORLD
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
How dynamic memory allocation is done using new and delete? Write a program for illustrating use of new and delete.
Answer
Dynamic memory allocation. Memory can be requested from the heap at run time with the new operator and returned with the delete operator. This lets the program decide the size of data during execution.
new
type *p = new type;allocates one variable.type *p = new type(value);allocates and initialises.type *p = new type[n];allocates an array ofnelements.- It returns the address of the block (and throws
bad_allocif memory is not available). For objects it also calls the constructor.
delete
delete p;frees a single object.delete[] p;frees an array.- It calls the destructor of the object and releases the memory. Memory not deleted causes a memory leak.
Program:
#include <iostream>
using namespace std;
int main() {
int *p = new int(25); // single integer
cout << "Value: " << *p << endl;
delete p;
int n;
cout << "Enter number of elements: ";
cin >> n;
int *arr = new int[n]; // dynamic array
cout << "Enter " << n << " numbers: ";
for (int i = 0; i < n; i++) cin >> arr[i];
int sum = 0;
for (int i = 0; i < n; i++) sum += arr[i];
cout << "Sum = " << sum << endl;
delete[] arr; // release the array
return 0;
}
Sample run with n = 3 and values 4 5 6 prints Value: 25 and Sum = 15.
Advantages over malloc/free: new is type safe, needs no sizeof or cast, and calls constructors; delete calls destructors.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2079 · 10 marks
Write short notes on:
- Friend Function
- Early binding and late binding
Answer
Friend function. A friend function is a non-member function that is given permission to access the private and protected members of a class. It is declared inside the class with the keyword friend, but it is defined outside and is called like a normal function (without an object and the dot operator).
Characteristics: it is not in the scope of the class; it cannot access members directly by name, so it must use an object (usually passed as an argument) and obj.member; it is not affected by the access specifiers; a friend can be a function of another class, or a function that works on objects of two classes.
#include <iostream>
using namespace std;
class Box {
int width;
public:
Box(int w) : width(w) {}
friend void printWidth(Box b);
};
void printWidth(Box b) {
cout << "Width = " << b.width << endl; // access to private member
}
int main() {
Box b(10);
printWidth(b); // Width = 10
return 0;
}
Early binding and late binding.
| Early (static) binding | Late (dynamic) binding |
|---|---|
| The function call is linked to its body at compile time | The call is linked to its body at run time |
| Used for ordinary functions, overloaded functions, operator overloading and non-virtual member functions | Used for virtual functions called through a base class pointer or reference |
| Faster, no vtable lookup | Slightly slower because of the vtable (virtual table) lookup |
| Basis of compile-time polymorphism | Basis of run-time polymorphism |
class A { public: virtual void show() { cout << "A"; } };
class B : public A { public: void show() { cout << "B"; } };
A *p = new B;
p->show(); // late binding: prints B, decided by the actual object type
If show() were not virtual, early binding would choose A::show() because the pointer type is A*.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
When inline functions may not work? Define and write syntax for default arguments. Write a program to display N number of characters by using default arguments for both parameters. Assume that the function takes two arguments, one character to be printed and other how many times the character to be printed respectively.
Answer
When inline functions may not work. The inline keyword is only a request. The compiler may ignore it, and the function is compiled as a normal function, when:
- the function contains a loop (
for,while,do-while), aswitchor agoto; - the function is recursive;
- the function contains
staticvariables; - the function body is large (code bloat would outweigh the saving);
- the function address is taken, or it is called through a function pointer;
- it is a virtual function called through a base pointer (the call is resolved at run time).
Default arguments. A default argument is a value given in the function declaration that the compiler uses automatically when the caller omits the corresponding argument. Defaults are assigned from right to left: once a parameter has a default, all parameters to its right must also have defaults.
Syntax:
return_type function_name(type1 p1, type2 p2 = value2, type3 p3 = value3);
Program (both parameters have defaults):
#include <iostream>
using namespace std;
void printChar(char ch = '*', int n = 10) {
for (int i = 0; i < n; i++)
cout << ch;
cout << endl;
}
int main() {
printChar(); // '*' printed 10 times
printChar('#'); // '#' printed 10 times
printChar('A', 5); // 'A' printed 5 times
return 0;
}
Output:
**********
##########
AAAAA
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 10 marks
What is constructor? Why constructor is needed in a class? Illustrate the types of constructor with an example.
Answer
Constructor. A constructor is a special member function that has the same name as the class, has no return type (not even void) and is called automatically when an object is created. It is normally public and may be overloaded.
Why it is needed.
- It initialises the data members when the object is created, so objects never hold garbage values.
- It removes the need to call a separate initialising function.
- It can acquire resources (memory, files) and set the object into a valid state.
- It allows different ways of initialising an object through overloading.
Types of constructors.
- Default constructor: takes no arguments (or all arguments have defaults).
- Parameterised constructor: takes arguments to initialise the object with given values.
- Copy constructor: creates a new object as a copy of an existing one; its form is
ClassName(const ClassName &obj). - (Also, if the programmer writes none, the compiler supplies an implicit default constructor.)
Example:
#include <iostream>
using namespace std;
class Rectangle {
int length, width;
public:
Rectangle() { // default
length = 1; width = 1;
}
Rectangle(int l, int w) { // parameterised
length = l; width = w;
}
Rectangle(const Rectangle &r) { // copy
length = r.length; width = r.width;
}
int area() { return length * width; }
};
int main() {
Rectangle r1; // default constructor
Rectangle r2(4, 5); // parameterised constructor
Rectangle r3(r2); // copy constructor
cout << r1.area() << endl; // 1
cout << r2.area() << endl; // 20
cout << r3.area() << endl; // 20
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Write a C++ program to display the number of objects created using static member.
Answer
A static data member is shared by all objects of the class. It is initialised to zero by default, and there is only one copy of it. The constructor increments it each time an object is created, and the destructor decrements it when an object is destroyed.
#include <iostream>
using namespace std;
class Counter {
static int count; // declaration
public:
Counter() { count++; }
~Counter() { count--; }
static void showCount() {
cout << "Objects alive: " << count << endl;
}
};
int Counter::count = 0; // definition outside the class
int main() {
Counter a, b;
Counter::showCount(); // 2
{
Counter c;
Counter::showCount(); // 3
} // c destroyed here
Counter::showCount(); // 2
return 0;
}
Output:
Objects alive: 2
Objects alive: 3
Objects alive: 2
The static member function showCount() can be called with the class name and can access only static members.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Explain about friend function and friend class with an example.
Answer
Friend function. A non-member function declared inside a class with the keyword friend can access the private and protected members of that class. It is called like an ordinary function, passing objects as arguments.
Friend class. If class B is declared as a friend of class A (friend class B; inside A), then all member functions of B can access the private and protected members of A. Friendship is not mutual (A does not get access to B) and is not inherited.
Example:
#include <iostream>
using namespace std;
class Account {
double balance;
public:
Account(double b) : balance(b) {}
friend void show(Account a); // friend function
friend class Auditor; // friend class
};
void show(Account a) {
cout << "Balance: " << a.balance << endl;
}
class Auditor {
public:
void addInterest(Account &a) {
a.balance += a.balance * 0.1; // accesses private data
}
};
int main() {
Account acc(1000);
show(acc); // Balance: 1000
Auditor au;
au.addInterest(acc);
show(acc); // Balance: 1100
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What is the use of reinterpret cast operator? Why do we need virtual function?
Answer
reinterpret_cast. reinterpret_cast<new_type>(expression) converts one pointer type to a completely unrelated pointer type, or a pointer to an integer and back, by reinterpreting the bit pattern. No check is made and no value conversion takes place, so it is unsafe and machine dependent. It is used in low-level code, for example to treat a block of memory as bytes, to print an address as an integer, or to work with hardware addresses.
int x = 65;
int *p = &x;
char *c = reinterpret_cast<char*>(p); // view the int as bytes
unsigned long addr = reinterpret_cast<unsigned long>(p);
Need for virtual functions. When a base class pointer or reference points to a derived class object, a normal call is bound at compile time to the base class version. A virtual function makes the call bound at run time according to the actual object type. We need it to achieve run-time polymorphism: one interface, different behaviour for each derived class (for example Shape* s; s->area(); calls the area of Circle or Rectangle as appropriate). It also allows extensible designs, since new derived classes work with the existing base-class code, and it is required for safe deletion of derived objects through a base pointer (virtual destructor).
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Differentiate between concrete class and abstract class. Define class template and function template with syntax.
Answer
Concrete class versus 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 to it |
| Used to represent real entities | Used as a base class that defines a common interface |
| Need not be inherited | Meant to be inherited; derived classes must override the pure virtual functions to become concrete |
Class template. A class template is a blueprint for a family of classes in which one or more data types are parameters. Syntax:
template <class T>
class ClassName {
T data;
public:
void set(T d) { data = d; }
T get() { return data; }
};
ClassName<int> a; // instantiation
ClassName<double> b;
Function template. A function template is a blueprint for a family of functions that differ only in the data type. Syntax:
template <class T>
T maxOf(T a, T b) {
return (a > b) ? a : b;
}
maxOf(3, 7); // T = int
maxOf(2.5, 1.2); // T = double
The keyword typename may be used in place of class.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Describe the chain of constructors and destructors in inheritance.
Answer
In inheritance, constructors and destructors are called in a fixed order, forming a chain through the class hierarchy.
Constructors are executed from the base class towards the derived class. When an object of a derived class is created, the constructor of the base class runs first (to build the base part), then the constructor of the derived class. In multilevel inheritance A -> B -> C, the order is A, B, C. In multiple inheritance, base constructors run in the order the bases are listed in the derived class declaration, then members' constructors, then the derived constructor. Arguments for the base constructor are passed through the initialiser list: Derived(int a, int b) : Base(a) { ... }. If none is given, the default constructor of the base is used.
Destructors are executed in the reverse order: the derived class destructor runs first, then the base class destructor. In A -> B -> C the order is C, B, A. For deleting a derived object through a base pointer, the base destructor must be virtual.
class A { public: A(){cout<<"A ";} ~A(){cout<<"~A ";} };
class B : public A { public: B(){cout<<"B ";} ~B(){cout<<"~B ";} };
class C : public B { public: C(){cout<<"C ";} ~C(){cout<<"~C ";} };
int main() { C obj; }
Output: A B C ~C ~B ~A
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
List any two operators that cannot be overloaded. Write a program to handle the possible exception in taking “age” as input. Here the exception must be thrown in the input is negative or greater than 200.
Answer
Operators that cannot be overloaded (any two): the scope resolution operator ::, the member access operator ., the pointer-to-member operator .*, the conditional operator ?:, and sizeof.
Exception handling for age input:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter age: ";
cin >> age;
try {
if (age < 0)
throw "Age cannot be negative";
if (age > 200)
throw "Age cannot be greater than 200";
cout << "Age accepted: " << age << endl;
}
catch (const char *msg) {
cout << "Exception: " << msg << endl;
}
return 0;
}
Sample runs:
- Input
25printsAge accepted: 25. - Input
-5printsException: Age cannot be negative. - Input
250printsException: Age cannot be greater than 200.
The throw statement transfers control out of the try block to the matching catch handler.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Create a class named Point with data members x(int) and y(int). Add operator overloading to find the Euclidean distance between two points.
Answer
The Euclidean distance between and is
Here the binary operator - is overloaded as a member function so that p1 - p2 returns the distance (a double).
#include <iostream>
#include <cmath>
using namespace std;
class Point {
int x, y;
public:
Point(int a = 0, int b = 0) : x(a), y(b) {}
double operator-(const Point &p) {
int dx = x - p.x;
int dy = y - p.y;
return sqrt(dx * dx + dy * dy);
}
};
int main() {
Point p1(1, 2), p2(4, 6);
cout << "Distance = " << p1 - p2 << endl;
return 0;
}
Check: , , so . Output: Distance = 5.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
Explain the reason for member function overriding when using virtual function.
Answer
Member function overriding means a derived class provides its own definition of a function that has the same name, parameters and return type as a function in the base class.
When the base function is declared virtual, overriding gives run-time polymorphism. The reasons are:
- A base class pointer or reference can point to a derived object. Without
virtual, the call is bound at compile time to the base version, whatever the object really is. Withvirtual, the call is resolved at run time (through the vtable) to the version of the actual object's class. - The derived class needs specialised behaviour for the same operation (for example
area()for Circle and Rectangle) while callers use one common interface. - It lets new derived classes be added without changing the code that uses the base pointer.
class Shape { public: virtual void draw() { cout << "Shape"; } };
class Circle : public Shape { public: void draw() { cout << "Circle"; } };
Shape *s = new Circle;
s->draw(); // prints Circle because draw() is virtual and overridden
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2080 · 5 marks
What do you mean by stream? Explain different stream class for file input/output.
Answer
Stream. A stream is an abstraction for a flow of data (a sequence of bytes) between a program and a source or destination such as the keyboard, screen, memory or a file. An input stream carries data into the program (cin); an output stream carries data out of it (cout). Streams make I/O device independent.
Stream classes for file input/output (declared in <fstream>, derived from ios through istream/ostream):
ifstream: input file stream, used to read from files. Providesopen(),get(),read(),getline(),seekg(),tellg(), and the extraction operator>>.ofstream: output file stream, used to write to files. Providesput(),write(),seekp(),tellp()and the insertion operator<<.fstream: supports both reading and writing on the same file, with all the functions above.filebuf: the buffer class that sets the file buffer and performs low-level reading and writing.
Example:
ofstream out("a.txt"); out << "Hi"; out.close();
ifstream in("a.txt"); string s; in >> s; in.close();
File modes such as ios::in, ios::out, ios::app, ios::binary and ios::trunc are given to open() or the constructor.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
What types of exception can be encountered in file handling? Write a program to create a class named MOVIE with data members name and genre. If the genre of the movie is comedy then write it to COMEDY.DAT and if the genre is action, write it to ACTION.DAT
Answer
(a) Exceptions in file handling.
- File not found / cannot be opened: opening a non-existent file for reading, or lacking permission or disk space for writing. Detected with
fail()or!file, oris_open(). - End of file reached: reading past the end of the file (
eof()becomes true). - Read/write error (bad bit): a hardware or irrecoverable error during transfer (
bad()). - Logical/format error: wrong data type read, such as reading text into an integer (
fail()). - Invalid file name or mode, or disk full.
- Invalid seek position (seeking beyond the file).
These are tested through the stream state functions good(), eof(), fail(), bad() and handled with try/throw/catch.
(b) Program:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class MOVIE {
char name[50];
char genre[20];
public:
void getData() {
cout << "Enter movie name: ";
cin.getline(name, 50);
cout << "Enter genre (comedy/action): ";
cin.getline(genre, 20);
}
const char* getGenre() { return genre; }
};
int main() {
MOVIE m;
m.getData();
try {
if (strcmp(m.getGenre(), "comedy") == 0) {
ofstream fout("COMEDY.DAT", ios::binary | ios::app);
if (!fout) throw "Cannot open COMEDY.DAT";
fout.write((char*)&m, sizeof(m));
fout.close();
cout << "Saved to COMEDY.DAT" << endl;
}
else if (strcmp(m.getGenre(), "action") == 0) {
ofstream fout("ACTION.DAT", ios::binary | ios::app);
if (!fout) throw "Cannot open ACTION.DAT";
fout.write((char*)&m, sizeof(m));
fout.close();
cout << "Saved to ACTION.DAT" << endl;
}
else {
cout << "Genre not handled." << endl;
}
}
catch (const char *msg) {
cout << "File error: " << msg << endl;
}
return 0;
}
The class holds only character arrays (no pointers or string), so the object can safely be written as a block of bytes with write().
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
Discuss the chain of constructor and destructor in derived class. Write a program to define a class named Employee with data members name, age and gender. Then create another class named EmployeeSalary inherited from Employee. In this class, the user should give the monthly salary of the employee and calculate the yearly salary after 15% tax deduction. In the main function, you should get the employee’s basic information and salary using inheritance.
Answer
(a) Chain of constructors and destructors in a derived class.
When an object of a derived class is created, constructors are called from the top of the hierarchy down: the base class constructor runs first, then the constructors of member objects, then the derived class constructor. Arguments for the base constructor are passed by the derived constructor's initialiser list, Derived(...) : Base(...). In multilevel inheritance A -> B -> C the order is A, B, C.
Destructors are called in exactly the reverse order: the derived class destructor first, then the base class destructor (C, B, A). The base destructor should be virtual when objects are deleted through base pointers.
(b) Program:
#include <iostream>
#include <string>
using namespace std;
class Employee {
protected:
string name;
int age;
char gender;
public:
void getInfo() {
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
cout << "Enter gender (M/F): ";
cin >> gender;
}
void showInfo() {
cout << "Name: " << name << ", Age: " << age
<< ", Gender: " << gender << endl;
}
};
class EmployeeSalary : public Employee {
double monthly;
double yearly;
public:
void getSalary() {
cout << "Enter monthly salary (Rs): ";
cin >> monthly;
}
void calculate() {
yearly = monthly * 12 * (1 - 0.15); // after 15% tax deduction
}
void showSalary() {
cout << "Monthly salary: Rs " << monthly << endl;
cout << "Yearly salary after 15% tax: Rs " << yearly << endl;
}
};
int main() {
EmployeeSalary e;
e.getInfo();
e.getSalary();
e.calculate();
e.showInfo();
e.showSalary();
return 0;
}
Check with monthly salary Rs 30000: yearly gross ; tax ; yearly salary after tax , which equals . Output shows Yearly salary after 15% tax: Rs 306000.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 10 marks
When do we use static member functions? Explain the types of constructors with an example.
Answer
(a) Static member functions. A static member function belongs to the class rather than to any object. It is declared with static, can access only static data members and other static member functions (it has no this pointer), and is called as ClassName::function().
We use it:
- to operate on static data members, such as a counter of objects created;
- when a function is needed without creating any object (utility or factory functions);
- to give access to private static data through a public interface.
class Student {
static int count;
public:
Student() { count++; }
static int getCount() { return count; }
};
int Student::count = 0;
// Student::getCount() can be called without any object
(b) Types of constructors.
- Default constructor: has no parameters (or all defaulted); initialises objects with fixed values.
- Parameterised constructor: takes parameters so each object can be initialised with different values.
- Copy constructor:
ClassName(const ClassName &obj); initialises a new object from an existing object. It is called when an object is initialised from another, passed or returned by value. - Dynamic constructor (allocates memory with
new) and constructor overloading are further forms.
#include <iostream>
using namespace std;
class Complex {
int re, im;
public:
Complex() { re = 0; im = 0; } // default
Complex(int r, int i) { re = r; im = i; } // parameterised
Complex(const Complex &c) { re = c.re; im = c.im; } // copy
void show() { cout << re << "+" << im << "i" << endl; }
};
int main() {
Complex a; // 0+0i
Complex b(3, 4); // 3+4i
Complex c(b); // 3+4i
a.show(); b.show(); c.show();
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a function template that returns the greater number between two integers.
Answer
A function template defines a generic function in which the data type is a parameter, so one definition works for all types that support the > operator.
#include <iostream>
using namespace std;
template <class T>
T greaterOf(T a, T b) {
return (a > b) ? a : b;
}
int main() {
int x, y;
cout << "Enter two integers: ";
cin >> x >> y;
cout << "Greater number = " << greaterOf<int>(x, y) << endl;
return 0;
}
Sample run: input 8 15 gives Greater number = 15.
The template is named greaterOf to avoid a clash with std::greater when using namespace std; is present.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Describe the characteristics of object oriented programming approach.
Answer
Object oriented programming (OOP) organises a program around objects that combine data and the functions that operate on it. Its main characteristics are:
- Objects and classes: a class is a blueprint and an object is an instance; the program is a set of interacting objects.
- Encapsulation: data and functions are wrapped together in a class.
- Data abstraction and hiding: only essential features are exposed through a public interface, and internal details are kept private, protecting data from accidental change.
- Inheritance: a derived class acquires properties and behaviour of a base class, giving code reuse and a hierarchy.
- Polymorphism: one name or operator has many forms, with compile-time (function and operator overloading) and run-time (virtual functions) types.
- Dynamic binding: the code executed for a call is decided at run time.
- Message passing: objects communicate by calling each other's member functions.
- Bottom-up approach: design starts with objects and builds up to the whole program, in contrast to the top-down approach of procedural programming.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
List the five types of storage classes with their keyword, lifetime, and visibility.
Answer
| Storage class | Keyword | Lifetime | Visibility (scope) |
|---|---|---|---|
| Automatic | auto (default for local variables) | Until the block in which it is declared ends | Local to the block |
| Register | register | Until the block ends; stored in a CPU register if possible | Local to the block |
| Static | static | Whole program execution; keeps its value between calls | Local to the block (static local) or to the file (static global) |
| External | extern | Whole program execution | Global; visible in all files that declare it extern |
| Mutable | mutable | Same as the object that contains it | Class member; can be modified even in a const object |
Note: since C++11 the keyword auto is used for type deduction, so auto as a storage class is no longer used in modern C++, and register is deprecated.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Write a program to create a class PERSON with data members name and age. Overload the greater than (>) symbol, to display the name of elder one.
Answer
The binary operator > is overloaded as a member function. It returns true if the calling object is older than the argument object, and the program then prints the name of the elder person.
#include <iostream>
#include <string>
using namespace std;
class PERSON {
string name;
int age;
public:
void getData() {
cout << "Enter name and age: ";
cin >> name >> age;
}
bool operator>(const PERSON &p) {
return age > p.age;
}
void showName() {
cout << name << endl;
}
};
int main() {
PERSON p1, p2;
p1.getData();
p2.getData();
cout << "Elder person: ";
if (p1 > p2)
p1.showName();
else if (p2 > p1)
p2.showName();
else
cout << "Both have the same age" << endl;
return 0;
}
Sample run: Ram 30 and Sita 25 print Elder person: Ram, because .
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Define virtual base class. Differentiate between function overloading and function overriding.
Answer
Virtual base class. When a class is derived through more than one path from the same base (multipath inheritance, the "diamond" problem), the grandchild receives multiple copies of the base members, which causes ambiguity. Declaring the base as virtual in the intermediate classes makes the compiler keep only one shared copy.
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 copy of A::x
int main() {
D d;
d.x = 10; // no ambiguity
}
Function overloading vs function overriding
| Function overloading | Function overriding |
|---|---|
| Same function name with different parameter lists (number, type or order) in the same scope. | Derived class redefines a base-class function with the same name and same signature. |
| Resolved at compile time (static binding). | Resolved at run time (dynamic binding) when the function is virtual. |
| Does not need inheritance. | Needs inheritance. |
| Return type alone cannot distinguish the functions. | Return type must be the same (or covariant). |
Example: int add(int,int); float add(float,float); | Example: Base::show() and Derived::show() |
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
What types of instructions are written in try block? Illustrate the use of friend function with an example.
Answer
Instructions in a try block. The try block contains the statements that may cause an exception, such as division by a possibly zero value, array access with an invalid index, memory allocation, file opening, or an explicit throw statement. If an exception is thrown, control leaves the try block and passes to the matching catch block; statements after the throw point in the try block are skipped.
try {
if (b == 0) throw "Division by zero";
cout << a / b;
}
catch (const char *msg) { cout << msg; }
Friend function. A friend function is a non-member function that is given access to the private and protected members of a class by declaring it with the keyword friend inside the class. It is called like a normal function, not through an object, and receives objects as arguments.
#include <iostream>
using namespace std;
class B; // forward declaration
class A {
int a;
public:
A(int x) : a(x) {}
friend int sum(A, B);
};
class B {
int b;
public:
B(int y) : b(y) {}
friend int sum(A, B);
};
int sum(A o1, B o2) { // accesses private data of both classes
return o1.a + o2.b;
}
int main() {
A x(10); B y(20);
cout << "Sum = " << sum(x, y); // Sum = 30
return 0;
}
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Create a class BOOK with data members name and price. Write a member function that will take two objects of BOOK class and return the object with lower price.
Answer
#include <iostream>
#include <cstring>
using namespace std;
class BOOK {
char name[50];
float price;
public:
void input() {
cout << "Enter name and price: ";
cin >> name >> price;
}
void display() {
cout << "Name: " << name << ", Price: Rs " << price << endl;
}
// takes two BOOK objects and returns the one with lower price
BOOK lower(BOOK b1, BOOK b2) {
return (b1.price < b2.price) ? b1 : b2;
}
};
int main() {
BOOK b1, b2, b3, result;
b1.input();
b2.input();
result = b3.lower(b1, b2);
cout << "Book with lower price:" << endl;
result.display();
return 0;
}
The member function lower() receives the two objects by value, compares their private price members (allowed because it is a member of the same class) and returns a copy of the cheaper object. The returned object is stored in result and displayed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Design a class TIME with hour and minutes. Write a program to convert integer type to TIME class type.
Answer
Conversion from a basic type (int) to a class type is done with a single-argument constructor. The constructor receives the total minutes and splits it into hours and minutes.
#include <iostream>
using namespace std;
class TIME {
int hour, minutes;
public:
TIME() { hour = minutes = 0; }
TIME(int t) { // int -> TIME conversion
hour = t / 60;
minutes = t % 60;
}
void display() {
cout << hour << " hr " << minutes << " min" << endl;
}
};
int main() {
int duration = 135;
TIME t1;
t1 = duration; // calls TIME(int)
t1.display(); // 2 hr 15 min
return 0;
}
For duration = 135, hour = 135 / 60 = 2 and minutes = 135 % 60 = 15, so the output is 2 hr 15 min.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2081 · 5 marks
Illustrate the advantage of return by reference with an example.
Answer
A function that returns by reference returns an alias (the actual variable) rather than a copy of its value. Advantages:
- No copy of the returned value is made, which saves time and memory for large objects.
- The function call can appear on the left side of an assignment, so the original variable can be modified through it.
- It allows chaining of operations (for example
cout << a << breturnsostream&).
#include <iostream>
using namespace std;
int &larger(int &a, int &b) {
return (a > b) ? a : b; // returns reference to the variable itself
}
int main() {
int x = 10, y = 25;
larger(x, y) = 0; // y (the larger) is set to 0
cout << "x = " << x << ", y = " << y; // x = 10, y = 0
return 0;
}
Because larger() returns a reference to y, assigning to the call modifies y itself, which is impossible with return by value. The returned variable must not be a local variable of the function, since it would be destroyed on return.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
A book shop maintains the inventory of books that are being sold at the shop. The list includes details such as author, title, price, publisher and stock position. Whenever a customer wants a book, the sales person inputs the title and author to the system. If it is not available, “Not found” message is displayed. If it is available, then the system displays the book details and requests for the number of copies required. If the requested copies are available, the total cost of the requested copies is displayed; otherwise “Required copies not in stock” is displayed. Design a system using a class called books with suitable member functions and constructors. Use new operator in constructors to allocate memory space required.
Answer
#include <iostream>
#include <cstring>
using namespace std;
class books {
char *author, *title, *publisher;
float price;
int stock;
public:
books() { // default constructor
author = new char[1]; author[0] = '\0';
title = new char[1]; title[0] = '\0';
publisher = new char[1]; publisher[0] = '\0';
price = 0; stock = 0;
}
books(const char *a, const char *t, const char *p, float pr, int s) {
author = new char[strlen(a) + 1]; strcpy(author, a);
title = new char[strlen(t) + 1]; strcpy(title, t);
publisher = new char[strlen(p) + 1]; strcpy(publisher, p);
price = pr; stock = s;
}
~books() { delete[] author; delete[] title; delete[] publisher; }
bool match(const char *t, const char *a) {
return strcmp(title, t) == 0 && strcmp(author, a) == 0;
}
void display() {
cout << "Author: " << author << "\nTitle: " << title
<< "\nPublisher: " << publisher << "\nPrice: Rs " << price
<< "\nStock: " << stock << endl;
}
void sell(int copies) {
if (copies <= stock) {
cout << "Total cost: Rs " << copies * price << endl;
stock -= copies;
} else
cout << "Required copies not in stock" << endl;
}
};
int main() {
const int N = 3;
books *shop[N];
shop[0] = new books("Balaguruswamy", "OOP with C++", "McGraw Hill", 650, 10);
shop[1] = new books("Kanetkar", "Let Us C", "BPB", 500, 5);
shop[2] = new books("Stroustrup", "The C++ Language", "Pearson", 1200, 2);
char t[50], a[50];
int copies;
cout << "Enter title: "; cin.getline(t, 50);
cout << "Enter author: "; cin.getline(a, 50);
int found = -1;
for (int i = 0; i < N; i++)
if (shop[i]->match(t, a)) { found = i; break; }
if (found == -1)
cout << "Not found" << endl;
else {
shop[found]->display();
cout << "Enter number of copies required: ";
cin >> copies;
shop[found]->sell(copies);
}
for (int i = 0; i < N; i++) delete shop[i];
return 0;
}
The constructors use new to allocate exactly the memory needed for each string, and the destructor releases it with delete[]. match() checks title and author, display() shows the book details, and sell() prints the total cost if enough copies exist, otherwise "Required copies not in stock".
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Define polymorphism? List its advantages, write program to perform basic to user defined data type conversion.
Answer
Polymorphism. Polymorphism means "many forms": the same name or operator behaves differently depending on the context (the types or objects involved). In C++ it is of two kinds: compile-time polymorphism (function overloading, operator overloading) and run-time polymorphism (virtual functions with base-class pointers).
Advantages
- The same interface can be used for different actions, so code is simpler and easier to read.
- Operators and functions can be extended to user-defined types (reusability and extensibility).
- Virtual functions let a base pointer call the correct derived-class function, so new classes can be added without changing existing code.
- Reduces the number of distinct names the programmer has to remember.
Basic to user-defined type conversion is done by a constructor with one argument of the basic type.
#include <iostream>
using namespace std;
class Distance {
int feet;
float inches;
public:
Distance() { feet = 0; inches = 0; }
Distance(float meters) { // float -> Distance
float totalInches = meters * 39.37;
feet = (int)(totalInches / 12);
inches = totalInches - feet * 12;
}
void display() {
cout << feet << " feet " << inches << " inches" << endl;
}
};
int main() {
float m = 2.5;
Distance d;
d = m; // basic -> user-defined, calls Distance(float)
d.display(); // 8 feet 2.425 inches
return 0;
}
Here 2.5 m = 98.425 inches, which is 8 feet and 2.425 inches.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 10 marks
Distinguish between public and private inheritance. Illustrate the chain of constructors and destructors in derived class with an example.
Answer
Public vs private inheritance
| Public inheritance | Private inheritance |
|---|---|
class D : public B | class D : private B |
| Public members of B stay public in D. | Public members of B become private in D. |
| Protected members of B stay protected in D. | Protected members of B become private in D. |
| Objects of D can call B's public functions directly. | Objects of D cannot call B's functions; only D's own member functions can. |
| Private members of B are never accessible in D. | Same. |
| Models an "is-a" relationship; further derived classes can still use B's members. | Models "implemented in terms of"; classes derived from D cannot access B's members. |
Chain of constructors and destructors. When a derived-class object is created, the base-class constructor runs first and then the derived-class constructor. When the object is destroyed, the order is reversed: the derived-class destructor runs first and then the base-class destructor. For multilevel inheritance, constructors run from the topmost base downwards and destructors in the opposite order.
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A constructor" << endl; }
~A() { cout << "A destructor" << endl; }
};
class B : public A {
public:
B() { cout << "B constructor" << endl; }
~B() { cout << "B destructor" << endl; }
};
class C : public B {
public:
C() { cout << "C constructor" << endl; }
~C() { cout << "C destructor" << endl; }
};
int main() {
C obj;
return 0;
}
Output:
A constructor
B constructor
C constructor
C destructor
B destructor
A destructor
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
List and describe the characteristics of object oriented programming.
Answer
Main characteristics of object-oriented programming:
- Object and class. An object is a run-time entity holding data and the functions that operate on it; a class is the blueprint (user-defined type) from which objects are created.
- Encapsulation. Data and functions are wrapped together in a single unit (the class).
- Data hiding / abstraction. Private data is accessible only through public member functions, protecting it from outside misuse. Abstraction exposes only essential features and hides implementation details.
- Inheritance. A new (derived) class acquires the properties of an existing (base) class, giving code reusability and a hierarchy of classes.
- Polymorphism. The same function name or operator performs different tasks in different contexts (overloading, virtual functions).
- Dynamic binding. The code executed for a function call is decided at run time, depending on the object type.
- Message passing. Objects communicate by sending messages, i.e. calling each other's member functions.
- Bottom-up approach. Programs are built by first designing classes and objects and then combining them, with emphasis on data rather than procedure.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Write any two types of storage class? Write a program to calculate Power (a, b), using default arguments, if second argument is omitted, then calculate square of a.
Answer
Storage classes (any two):
- auto: default for local variables; created when the block is entered and destroyed on leaving it; scope is the block.
- static: a local static variable keeps its value between function calls and is initialised only once; a global static variable is visible only in its file. Lifetime is the whole program.
- (Others:
registerrequests storage in a CPU register;externrefers to a global variable defined in another file.)
Program with default argument
#include <iostream>
using namespace std;
long power(int a, int b = 2) { // if b is omitted, square of a
long result = 1;
for (int i = 1; i <= b; i++)
result *= a;
return result;
}
int main() {
cout << "power(5, 3) = " << power(5, 3) << endl; // 125
cout << "power(5) = " << power(5) << endl; // 25
return 0;
}
When power(5) is called, the compiler supplies the default value b = 2, so the square 25 is calculated.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Explain copy constructor with an example.
Answer
A copy constructor is a constructor that initialises a new object from an existing object of the same class. Its parameter is a reference to an object of the same class: ClassName(const ClassName &obj). It is called when
- an object is initialised from another (
A b(a);orA b = a;), - an object is passed to a function by value,
- an object is returned by value.
If the programmer does not write one, the compiler supplies a default copy constructor that copies member by member (shallow copy). A user-defined copy constructor is needed when the class holds dynamically allocated memory, so that a deep copy is made.
#include <iostream>
#include <cstring>
using namespace std;
class Student {
char *name;
int roll;
public:
Student(const char *n, int r) {
name = new char[strlen(n) + 1];
strcpy(name, n);
roll = r;
}
Student(const Student &s) { // copy constructor (deep copy)
name = new char[strlen(s.name) + 1];
strcpy(name, s.name);
roll = s.roll;
}
~Student() { delete[] name; }
void display() { cout << name << " " << roll << endl; }
};
int main() {
Student s1("Ram", 1);
Student s2(s1); // copy constructor called
s1.display();
s2.display();
return 0;
}
Both objects hold the same values but separate memory for name, so destroying one does not affect the other.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Is multiple inheritance possible? List some advantages and disadvantages of inheritance.
Answer
Multiple inheritance is possible in C++. A class can be derived from two or more base classes, for example class C : public A, public B { };. (Java does not allow it for classes, but C++ does.)
Advantages of inheritance
- Reusability: existing code of the base class is reused without rewriting.
- Saves development time and reduces errors since tested code is reused.
- Supports extensibility: new features are added in derived classes without changing the base class.
- Represents real-world hierarchies naturally and supports polymorphism.
- Easier maintenance: a change in the base class is reflected in all derived classes.
Disadvantages of inheritance
- Tight coupling between base and derived classes; a change in the base class may break derived classes.
- Multiple and multipath inheritance can cause ambiguity (the diamond problem) and complicated design.
- Deep hierarchies are hard to understand and debug.
- Slightly slower execution because of extra function calls and virtual-function overhead.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Assume that there are three animals in which snake make sound as “hiss”, dog make sound as “raf – raf” and cat as “meow”. Now implement this concept using pure virtual function.
Answer
A pure virtual function is declared in the base class as virtual void f() = 0; and has no body. A class containing one is abstract and cannot be instantiated; each derived class must override the function. The program below uses an abstract class Animal with a pure virtual function sound().
#include <iostream>
using namespace std;
class Animal {
public:
virtual void sound() = 0; // pure virtual function
virtual ~Animal() {}
};
class Snake : public Animal {
public:
void sound() { cout << "hiss" << endl; }
};
class Dog : public Animal {
public:
void sound() { cout << "raf - raf" << endl; }
};
class Cat : public Animal {
public:
void sound() { cout << "meow" << endl; }
};
int main() {
Animal *a[3];
a[0] = new Snake;
a[1] = new Dog;
a[2] = new Cat;
for (int i = 0; i < 3; i++) {
a[i]->sound(); // run-time (dynamic) binding
delete a[i];
}
return 0;
}
Output:
hiss
raf - raf
meow
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
What are the uses of try and catch block? Write a program to throw an exception if the string given by user does not start with vowel.
Answer
Uses of try and catch. Exception handling separates error-handling code from normal code. The try block contains the statements that may generate an exception; when an error occurs the program uses throw to raise an exception object. The catch block immediately following the try block receives and handles that exception (matched by type), so the program can report the error and continue or terminate gracefully instead of crashing. Several catch blocks, or catch(...), can handle different exception types.
Program
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char str[100];
cout << "Enter a string: ";
cin >> str;
try {
char c = tolower(str[0]);
if (c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u')
throw str[0]; // throws a char
cout << "String starts with a vowel" << endl;
}
catch (char ch) {
cout << "Exception: string starts with '" << ch
<< "', which is not a vowel" << endl;
}
return 0;
}
For input apple the message "String starts with a vowel" is printed; for book the exception is thrown and caught by the catch block.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
How do you access file randomly? How do you test errors during file operations?
Answer
Random access to a file. A file can be accessed at any position (not only sequentially) by moving the file pointers with seek functions:
seekg(offset, reference)moves the get (read) pointer;seekp(offset, reference)moves the put (write) pointer.- The reference position is
ios::beg(start),ios::cur(current) orios::end(end). tellg()andtellp()return the current position of the get and put pointers.
fstream f("data.dat", ios::in | ios::out | ios::binary);
f.seekg(n * sizeof(Student), ios::beg); // jump to the (n+1)th record
f.read((char*)&s, sizeof(s));
Testing errors during file operations. The stream class keeps status flags, which are tested with these member functions:
| Function | Returns true when |
|---|---|
eof() | end of file has been reached |
fail() | an input/output operation failed (e.g. invalid format, or the file could not be opened) |
bad() | a serious, unrecoverable error occurred |
good() | no error has occurred |
The file object can also be tested directly, for example if (!f) cout << "Error";, and is_open() checks whether a file was opened successfully:
ifstream fin("abc.txt");
if (!fin.is_open()) cout << "Cannot open file";
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Define stream. Suppose a file named STD.DAT contains a list of objects of class Student having data members name and class. Now write a program to extract the name of students reading in class 5 from STD.DAT.
Answer
Stream. A stream is a sequence of bytes that flows between the program and an input or output device (keyboard, screen, file). Input streams (istream, ifstream) carry data into the program and output streams (ostream, ofstream) carry data out of it. In C++ the stream classes are declared in <iostream> and <fstream>.
Program
#include <iostream>
#include <fstream>
using namespace std;
class Student {
char name[30];
int cls;
public:
int getClass() { return cls; }
void showName() { cout << name << endl; }
};
int main() {
ifstream fin("STD.DAT", ios::in | ios::binary);
if (!fin) {
cout << "Cannot open file" << endl;
return 1;
}
Student s;
cout << "Students reading in class 5:" << endl;
while (fin.read((char*)&s, sizeof(s))) {
if (s.getClass() == 5)
s.showName();
}
fin.close();
return 0;
}
The file is read record by record into an object of class Student; whenever the class value is 5, the student's name is printed.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
- 2082 · 5 marks
Explain the use of ‘this’ pointer. Why do we need function template?
Answer
The this pointer. this is an implicit pointer available inside every non-static member function; it holds the address of the object that invoked the function. Uses:
- To distinguish data members from parameters with the same name:
this->x = x; - To return the invoking object itself, e.g.
return *this;, which allows chaining of calls such asobj.set(1).set(2). - In operator overloading, to access the left-hand operand, and to compare an object with the argument (
if (this == &obj)).
class Point {
int x;
public:
Point &setX(int x) { this->x = x; return *this; }
};
Need for function templates. Overloaded functions that perform the same logic on different data types (for example finding the larger of two int, float or char values) would otherwise need to be written repeatedly. A function template defines one generic function with a type parameter, and the compiler generates the correct version for each type used.
template <class T>
T larger(T a, T b) { return (a > b) ? a : b; }
// larger(3, 7) -> int version, larger(2.5, 1.2) -> double version
Benefits: less code duplication, type safety, easier maintenance and reusability.
Answer checked by Claude Sonnet · Oct 21, 2026
Test yourself · 2 MCQs
Loading…
Questions from TU BSc CSIT 2075 Second Semester Discrete Structures (TU IOST board exam, 2075), TU BSc CSIT 2076 Second Semester Discrete Structures (TU IOST board exam, 2076), TU BSc CSIT 2078 Second Semester Discrete Structures (TU IOST board exam, 2078), TU BSc CSIT 2079 Second Semester Discrete Structures (TU IOST board exam, 2079), TU BSc CSIT 2080 Second Semester Discrete Structures (TU IOST board exam, 2080), TU BSc CSIT 2081 Second Semester Discrete Structures (TU IOST board exam, 2081), TU BSc CSIT 2082 Second Semester Discrete Structures (TU IOST board exam, 2082), TU BSc CSIT 2075 Second Semester Mathematics II (TU IOST board exam, 2075), TU BSc CSIT 2076 Second Semester Mathematics II (TU IOST board exam, 2076), TU BSc CSIT 2078 Second Semester Mathematics II (TU IOST board exam, 2078), TU BSc CSIT 2079 Second Semester Mathematics II (TU IOST board exam, 2079), TU BSc CSIT 2080 Second Semester Mathematics II (TU IOST board exam, 2080), TU BSc CSIT 2081 Second Semester Mathematics II (TU IOST board exam, 2081), TU BSc CSIT 2082 Second Semester Mathematics II (TU IOST board exam, 2082), TU BSc CSIT 2075 Second Semester Microprocessor (TU IOST board exam, 2075), TU BSc CSIT 2076 Second Semester Microprocessor (TU IOST board exam, 2076), TU BSc CSIT 2078 Second Semester Microprocessor (TU IOST board exam, 2078), TU BSc CSIT 2079 Second Semester Microprocessor (TU IOST board exam, 2079), TU BSc CSIT 2080 Second Semester Microprocessor (TU IOST board exam, 2080), TU BSc CSIT 2081 Second Semester Microprocessor (TU IOST board exam, 2081), TU BSc CSIT 2082 Second Semester Microprocessor (TU IOST board exam, 2082), TU BSc CSIT 2075 Second Semester Object Oriented Programming (C++) (TU IOST board exam, 2075), TU BSc CSIT 2076 Second Semester Object Oriented Programming (C++) (TU IOST board exam, 2076), TU BSc CSIT 2078 Second Semester Object Oriented Programming (C++) (TU IOST board exam, 2078), TU BSc CSIT 2079 Second Semester Object Oriented Programming (C++) (TU IOST board exam, 2079), TU BSc CSIT 2080 Second Semester Object Oriented Programming (C++) (TU IOST board exam, 2080), TU BSc CSIT 2081 Second Semester Object Oriented Programming (C++) (TU IOST board exam, 2081), TU BSc CSIT 2082 Second Semester Object Oriented Programming (C++) (TU IOST board exam, 2082), TU BSc CSIT 2075 Second Semester Statistics I (TU IOST board exam, 2075), TU BSc CSIT 2076 Second Semester Statistics I (TU IOST board exam, 2076), TU BSc CSIT 2078 Second Semester Statistics I (TU IOST board exam, 2078), TU BSc CSIT 2079 Second Semester Statistics I (TU IOST board exam, 2079), TU BSc CSIT 2080 Second Semester Statistics I (TU IOST board exam, 2080), TU BSc CSIT 2081 Second Semester Statistics I (TU IOST board exam, 2081) and TU BSc CSIT 2082 Second Semester Statistics I (TU IOST board exam, 2082). Answers are written for this site; check them against your class notes.