ENDSEMC
ENDSEMC
a) This pointer
this is an implicit pointer available in non-static
member functions.
It points to the current calling object.
Useful for returning object reference or resolving
variable shadowing.
b) What is inheritance? Explain types of a) Explain memory management operators with
inheritance. the help of suitable example.
Inheritance is a mechanism where one class In C++, new and delete are memory management
(derived) acquires properties and behaviors of operators.
another class (base). new dynamically allocates memory during runtime,
It promotes code reusability and establishes while delete frees it.
relationships between classes. Example:
Types include: int *ptr = new int; // allocates memory
Single (one base, one derived) *ptr = 10;
Multiple (more than one base) delete ptr; // deallocates memory
Multilevel (derived from derived) They help manage heap memory safely.
Hierarchical (one base, multiple derived) b) Explain memory allocation for objects with non-
Hybrid (combination of types) static and static data members.
c) Explain static data members and static member Each object of a class has its own copy of non-static
functions with example. data members, stored on the stack or heap.
Static members are shared among all objects of a Static data members are shared among all objects
class. and are stored in static storage.
A static data member is declared using the static They are initialized outside the class definition.
keyword and initialized outside the class. Accessed using the class name rather than an
Static functions can only access static data object.
members. c) When do we make a class virtual base class?
Example: Explain with suitable example.
class Test { static int count; static void show(); }; A virtual base class is used in multiple inheritance
d) What is friend function? Write characteristics of to avoid duplication of base class members.
friend function. It resolves the diamond problem by sharing a single
A friend function is not a member of the class but instance of the base class.
has access to its private and protected data. Syntax:
It is declared using the friend keyword inside the class A {};
class. class B : virtual public A {};
Characteristics: class C : virtual public A {};
Not called using an object class D : public B, public C {};
Doesn't belong to any object d) Explain array of object in C++ with example.
Helps in operator overloading when access to An array of objects is a collection of instances of a
private members is needed class stored in contiguous memory.
Increases coupling but is useful in special cases It allows handling multiple objects using indexing.
e) Explain use of any four file opening modes. Example:
ios::in – Opens a file for reading. class Student { public: void show(); };
ios::out – Opens a file for writing (creates file if not Student s[3]; // array of 3 Student objects
exists). e) Explain any four formatted input/output
ios::app – Opens a file and appends data to the functions.
end. setw(n) – Sets field width for output.
ios::binary – Opens a file in binary mode for setprecision(n) – Sets number of digits after
reading/writing binary data. decimal.
These modes are used with fstream objects during showpoint – Forces decimal point to be displayed.
file operations. fixed – Uses fixed-point notation for floating-point
values.
These manipulators are included in <iomanip> and
enhance output formatting.
a) Explain operator overloading in C++ with an It supports code reuse in related subclasses.
example. Example:
Operator overloading allows custom definitions of class Animal {};
operators for user-defined types. class Dog : public Animal {};
It improves code readability by allowing intuitive
expressions. class Cat : public Animal {};
Example: a) List different types of constructor. Explain any
class Complex { one constructor with example.
int real, imag; Types of constructors:
Complex operator+(Complex c) { return Default constructor
Complex(real + c.real, imag + c.imag); } Parameterized constructor
}; Copy constructor
b) Explain memory allocation for objects with non- Dynamic constructor
static and static data members. Example (Parameterized):
Non-static data members are part of each object’s class A {
memory allocation. int x;
Static members exist only once, regardless of how A(int a) { x = a; }
many objects are created. };
They are stored in static memory and shared across b) What is function overloading? Explain with
all objects. suitable example.
Access to static members is done using the class Function overloading means creating multiple
name. functions with the same name but different
c) What is pure virtual function? Explain with the parameters.
help of example. It helps in code readability and modular design.
A pure virtual function is declared using = 0 and has Example:
no definition in the base class. void display(int);
It forces derived classes to implement the function, void display(double);
making the base class abstract. c) Describe different types of inheritance.
Example: Single – One base and one derived class.
class Shape { virtual void draw() = 0; }; Multilevel – Derived class inherits another derived
class Circle : public Shape { void draw() { /*...*/ } }; class.
d) Explain dynamic constructor with suitable Multiple – One class inherits from more than one
example. base class.
A dynamic constructor allocates memory at Hierarchical – Multiple classes inherit from one
runtime using the new operator. base.
It is useful when the size or content of an object Hybrid – Combination of more than one type.
depends on input. d) Explain virtual base class with suitable diagram.
Example: Used to avoid duplication when multiple derived
class Array { classes inherit from a common base.
int *arr; Declared using virtual keyword.
Array(int n) { arr = new int[n]; } Example:
}; class A {};
e) What is inheritance and explain hierarchical class B : virtual public A {};
inheritance. class C : virtual public A {};
Inheritance allows reuse of code by creating new class D : public B, public C {};
classes from existing ones.
In hierarchical inheritance, multiple derived classes
inherit from a single base class.
e) Describe file manipulators with their syntaxes. private:
File manipulators format file input/output. string designation, department;
Examples: float basicSalary;
ios::in – open file for reading public:
ios::out – open file for writing void accept() {
ios::app – append mode Employee::accept();
ios::binary – binary mode cout << "Enter designation, department, and
Syntax: basic salary: ";
fstream file; cin >> designation >> department >>
file.open("data.txt", ios::out | ios::app); basicSalary;
}
b) C++ Program to Design a Class Hierarchy for void display() {
Person, Employee, and Manager: Employee::display();
#include <iostream> cout << "Designation: " << designation << ",
using namespace std; Department: " << department << ", Basic Salary: "
<< basicSalary << endl;
class Person { }
protected: float getSalary() {
string name, address, phoneNo; return basicSalary;
public: }
void accept() { };
cout << "Enter name, address, phone number:
"; int main() {
cin >> name >> address >> phoneNo; int n;
} cout << "Enter number of managers: ";
void display() { cin >> n;
cout << "Name: " << name << ", Address: " << Manager m[n];
address << ", Phone: " << phoneNo << endl; for (int i = 0; i < n; i++) {
} m[i].accept();
}; }
int highestSalaryIdx = 0;
class Employee : public Person { for (int i = 1; i < n; i++) {
protected: if (m[i].getSalary() >
int eno; m[highestSalaryIdx].getSalary()) {
string ename; highestSalaryIdx = i;
public: }
void accept() { }
Person::accept(); cout << "Manager with highest salary: ";
cout << "Enter employee number and name: "; m[highestSalaryIdx].display();
cin >> eno >> ename; return 0;
} }
void display() {
Person::display();
cout << "Employee number: " << eno << ",
Employee name: " << ename << endl;
}
};
int DisplayCounter::count = 0;
int main() {
DisplayCounter d1, d2;
d1.display();
d2.display();
d1.display();
return 0;
}
e) C++ Program to Read Contents of a Text File and a) C++ Program to Create a Class with Two Data
Count the Number of Characters, Words, and Members and Swap Two Numbers Using Call by
Lines: Reference:
#include <iostream> #include <iostream>
#include <fstream> using namespace std;
#include <cctype>
using namespace std; class SwapNumbers {
int a, b;
int main() { public:
ifstream fin("input.txt"); void accept() {
if (!fin) { cout << "Enter two numbers: ";
cout << "Error opening file!" << endl; cin >> a >> b;
return 1; }
} void display() {
cout << "a = " << a << ", b = " << b << endl;
char ch; }
int chars = 0, words = 0, lines = 0; void swap(SwapNumbers &n) {
bool inWord = false; int temp = n.a;
n.a = n.b;
while (fin.get(ch)) { n.b = temp;
chars++; }
if (ch == '\n') lines++; };
if (isspace(ch)) {
if (inWord) words++; int main() {
inWord = false; SwapNumbers sn;
} else { sn.accept();
inWord = true; cout << "Before swap: ";
} sn.display();
} sn.swap(sn);
cout << "After swap: ";
if (inWord) words++; // Count last word if file sn.display();
doesn't end with space/newline return 0;
}
fin.close();
cout << "Characters: " << chars << " Words: " <<
words << " Lines: " << lines << endl;
return 0;
}
b) C++ Program to Create a Class Customer with c) C++ Program to Calculate Factorial of an Integer
Information and Display the Customer with Number Using Inline Function:
Maximum Salary: #include <iostream>
#include <iostream> using namespace std;
using namespace std;
inline int factorial(int n) {
class Customer { int fact = 1;
int C_id; for (int i = 1; i <= n; i++)
string C_name; fact *= i;
float C_Salary; return fact;
public: }
void accept() {
cout << "Enter Customer ID, Name, Salary: "; int main() {
cin >> C_id >> C_name >> C_Salary; int num;
} cout << "Enter number: ";
void display() { cin >> num;
cout << "Customer ID: " << C_id << ", Name: " cout << "Factorial: " << factorial(num) << endl;
<< C_name << ", Salary: " << C_Salary << endl; return 0;
} }
float getSalary() { d) C++ Program to Count the Number of Times
return C_Salary; count() is Called Using Static Data Member:
} #include <iostream>
}; using namespace std;
int main() {
String s1, s2;
s1.accept();
s2.accept();
if (s1 == s2)
cout << "Strings are equal." << endl;
else
cout << "Strings are not equal." << endl;
c) Explain Virtual Base Class with Example }
Definition: When multiple derived classes inherit e) Overload Binary + Operator for String
from the same base class, and another class Concatenation:
inherits from them, it may result in duplication of #include <iostream>
base class. To avoid this, use virtual inheritance. #include <cstring>
Example: using namespace std;
#include <iostream>
using namespace std; class String {
char str[100];
class A { public:
public: void accept() {
int x; cout << "Enter string: ";
}; cin >> str;
}
class B : virtual public A {
}; String operator+(String s) {
String temp;
class C : virtual public A { strcpy(temp.str, str);
}; strcat(temp.str, s.str);
return temp;
class D : public B, public C { }
};
void display() {
int main() { cout << "Concatenated String: " << str << endl;
D obj; }
obj.x = 100; // No ambiguity due to virtual base };
class
cout << "Value of x: " << obj.x << endl; int main() {
return 0; String s1, s2, s3;
} s1.accept();
Explanation: s2.accept();
Class A is virtually inherited by B and C. s3 = s1 + s2;
D inherits B and C, but there's only one copy of A in s3.display();
D. return 0;
d) Program to Find Maximum of Two Integers }
Using Function Template:
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
cout << "Maximum is: " << maximum(x, y) <<
endl;
return 0;
a) Can we pass class object as function c) What is Class Template? Explain with syntax and
arguments? Explain with the help of an example: example
Yes, class objects can be passed to functions in Definition: A class template allows you to create a
three ways: generic class that can work with different data
By value types.
By reference Syntax:
By address (pointer) template <class T>
Example (pass by reference): class ClassName {
#include <iostream> T data;
using namespace std; public:
void setData(T d) {
class Sample { data = d;
int a, b; }
public: void showData() {
void accept(int x, int y) { cout << "Data = " << data << endl;
a = x; }
b = y; };
} Example:
void display() { #include <iostream>
cout << "a = " << a << ", b = " << b << endl; using namespace std;
}
template <class T>
void add(Sample &s2) { class Number {
a += s2.a; T num;
b += s2.b; public:
} void set(T n) {
}; num = n;
}
int main() { void show() {
Sample s1, s2; cout << "Number = " << num << endl;
s1.accept(5, 10); }
s2.accept(3, 6); };
s1.add(s2); // Passing object s2 to s1
s1.display(); int main() {
return 0; Number<int> n1;
} n1.set(10);
b) Explain various stream classes used to perform n1.show();
console I/O operations
In C++, iostream is the main header file for console Number<float> n2;
I/O. It includes these stream classes: n2.set(15.5);
Class Description n2.show();
istream Input stream class (e.g. cin)
return 0;
ostream Output stream class (e.g. cout) }
iostream Supports both input and output
ifstream Input file stream (used for file input)
ofstream Output file stream (used for file output)
fstream Supports both file input/output
d) Program to perform addition of two matrices Example (Pass by Reference):
using operator overloading: #include <iostream>
#include <iostream> using namespace std;
using namespace std; class Number {
int a;
class Matrix { public:
int a[2][2]; void set(int x) {
public: a = x;
void accept() { }
cout << "Enter 4 elements of 2x2 matrix:\n"; void add(Number &n) { // object passed by
for(int i=0; i<2; i++) reference
for(int j=0; j<2; j++) a = a + n.a;
cin >> a[i][j]; }
} void show() {
cout << "Value: " << a << endl;
Matrix operator+(Matrix m) { }
Matrix temp; };
for(int i=0; i<2; i++) int main() {
for(int j=0; j<2; j++) Number n1, n2;
temp.a[i][j] = a[i][j] + m.a[i][j]; n1.set(10);
return temp; n2.set(20);
} n1.add(n2); // n2 is passed as object
n1.show(); // Output: 30
void display() { return 0;
cout << "Matrix:\n"; }
for(int i=0; i<2; i++) { b) Explain different characteristics of friend
for(int j=0; j<2; j++) function.
cout << a[i][j] << " "; A friend function is a non-member function that
cout << endl; can access private and protected members of a
} class.
} Characteristics:
}; Not a member: It’s not a class member but has
access rights.
int main() { Declared using friend keyword inside the class.
Matrix m1, m2, m3; Can be defined anywhere (inside or outside class).
m1.accept(); Used for operator overloading and two-class
m2.accept(); operations.
m3 = m1 + m2; Cannot be called using object.
m3.display(); Example:
return 0; class A {
} int a;
a) Explain object as function arguments. Explain public:
with the help of an example program. A() { a = 10; }
In C++, objects can be passed to functions to access friend void show(A);
their data members or perform operations. There };
are three ways to pass an object:
Pass by Value void show(A obj) {
Pass by Reference cout << "Value of a is: " << obj.a << endl;
Pass by Address (Pointer) }
c) What is class Template? Explain syntax of class void getData(string s) {
template with suitable example. str = s;
A class template is used to create a class that can }
work with any data type.
Syntax: StringAdder operator+(StringAdder s2) {
template <class T> StringAdder temp;
class ClassName { temp.str = str + s2.str;
T data; return temp;
public: }
void setData(T d) { data = d; }
void showData() { cout << data; } void show() {
}; cout << "Concatenated String: " << str << endl;
Example: }
#include <iostream> };
using namespace std;
int main() {
template <class T> StringAdder s1, s2, s3;
class Box { s1.getData("Hello ");
T value; s2.getData("World");
public: s3 = s1 + s2;
void set(T val) { s3.show();
value = val; return 0;
} }
b) Explain try, catch, and throw in exception
void show() { handling.
cout << "Value = " << value << endl; In C++, exception handling is used to handle
} runtime errors using three keywords:
}; try: Block of code to monitor for errors.
throw: Used to throw an exception when an error
int main() { occurs.
Box<int> intBox; catch: Block of code that handles the exception.
intBox.set(100); Example:
intBox.show(); #include <iostream>
using namespace std;
Box<float> floatBox;
floatBox.set(12.5); int main() {
floatBox.show(); int a = 10, b = 0;
try {
return 0; if (b == 0)
} throw "Division by zero error!";
d) Write a program to overload binary + operator cout << "Result: " << a / b;
to add two strings. } catch (const char* msg) {
#include <iostream> cout << "Exception caught: " << msg << endl;
#include <string> }
using namespace std; return 0;
}
class StringAdder {
string str;
public:
c) Design C++ class which contains function };
display(). Write a program to count number of
times display() function is called (Use static data int main() {
member). Demo d1; // constructor called
#include <iostream> return 0; // destructor called automatically
using namespace std; }
e) What is tokens in C++? Explain in detail.
class Counter { Tokens are the smallest units in a C++ program. A
static int count; // static data member C++ compiler breaks code into meaningful tokens
public: during compilation.
void display() { Types of Tokens:
count++; Keywords – Reserved words (e.g., int, class, return)
cout << "Display called " << count << " times." Identifiers – Names of variables, functions, classes
<< endl; (e.g., sum, main)
} Constants – Fixed values (e.g., 10, 3.14, 'A')
}; Operators – Symbols that perform operations (e.g.,
+, -, =)
int Counter::count = 0; // initialize static member Punctuators/Symbols – Special symbols (e.g., ;, {},
())
int main() { Strings – Text inside double quotes (e.g., "Hello")
Counter c1, c2; Example:
c1.display(); // 1 int a = 10;
c2.display(); // 2 Here:
c1.display(); // 3 int → keyword
return 0; a → identifier
} = → operator
d) What is Destructor? State the importance of 10 → constant
destructor with example. ; → punctuator
A destructor is a special member function that is
automatically invoked when an object goes out of
scope. It cleans up memory and resources used by
the object.
Characteristics:
Same name as class preceded by ~
No return type and no parameters
Automatically called
Example:
#include <iostream>
using namespace std;
class Demo {
public:
Demo() {
cout << "Constructor called" << endl;
}
~Demo() {
cout << "Destructor called" << endl;
}
a) C++ Program to Create a Class Product for Bill
Generation:
#include <iostream>
using namespace std;
class Product {
string pname;
float price;
int quantity;
public:
void accept() {
cout << "Enter product name, price, and
quantity: ";
cin >> pname >> price >> quantity;
}
void display() {
cout << "Product: " << pname << ", Price: " <<
price << ", Quantity: " << quantity << endl;
}
float calculateBill() {
return price * quantity;
}
};
int main() {
int n;
cout << "Enter the number of products: ";
cin >> n;
Product p[n];
float totalBill = 0;
for (int i = 0; i < n; i++) {
p[i].accept();
totalBill += p[i].calculateBill();
}
cout << "Total bill: " << totalBill << endl;
return 0;
}