0% found this document useful (0 votes)
34 views

Cpp Paper Solutions

The document covers various concepts of C++ programming including encapsulation, inline functions, classes, constructors, and inheritance. It explains memory management operators, friend functions, polymorphism, templates, file handling, and exception handling. Additionally, it discusses object-oriented programming features, pure virtual functions, and manipulators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Cpp Paper Solutions

The document covers various concepts of C++ programming including encapsulation, inline functions, classes, constructors, and inheritance. It explains memory management operators, friend functions, polymorphism, templates, file handling, and exception handling. Additionally, it discusses object-oriented programming features, pure virtual functions, and manipulators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

CPP PAPER-1

Q-1

a) Define Encapsulation.
Encapsulation is the process of wrapping data and functions into a single unit called a class. It
helps in data hiding and protects object integrity by restricting direct access.

b) What is inline function?


An inline function is a function where the compiler replaces the function call with the actual
code of the function, reducing function call overhead.

c) What is Class? Give its syntax.


A class is a user-defined data type that encapsulates data and functions.
Syntax:

class ClassName {
// data members
// member functions
};

d) What is Constructor?
A constructor is a special member function automatically called when an object is created. It
initializes the object’s data members.

e) Explain any two use of Scope Resolution operator.

1. To define a function outside the class.


2. To access a global variable when a local variable has the same name.

f) List the operators which cannot be overloaded.


The following operators cannot be overloaded:

1. :: (Scope Resolution)
2. . (Member Access)
3. .* (Pointer-to-member)
4. sizeof
g) What is virtual function?
A virtual function is a member function in a base class that can be overridden in a derived
class. It supports runtime polymorphism.

h) What is stream?
A stream is an abstraction that represents a flow of data, either input or output. For example,
cin for input and cout for output in C++.

i) Explain get() and put() function.

 get() is used to read a single character from an input stream.


 put() is used to write a single character to an output stream.

j) What are the access specifiers used in C++?


The access specifiers in C++ are:

1. public – Accessible from anywhere.


2. private – Accessible only within the class.
3. protected – Accessible within the class and its derived classes.

Q-2

a) Explain Memory management operators in detail.


In C++, memory management is done using two operators:

1. new Operator:
o Allocates memory at runtime on the heap.
o Returns the address of the allocated memory.
o Syntax:
o int* ptr = new int; // Allocates memory for an integer

2. delete Operator:
o Frees the memory allocated using new.
o Prevents memory leaks.
o Syntax:
o delete ptr; // Deallocates memory

For arrays:

int* arr = new int[5]; // Allocates array


delete[] arr; // Deallocates array

b) What is friend function? Explain with an example?


A friend function is a function that is not a member of a class but has access to its private
and protected members. It is declared using the friend keyword inside the class.

Example:

#include <iostream>
using namespace std;

class Box {
private:
int length;
public:
Box() : length(0) {}
friend void showLength(Box); // Declaration
};

void showLength(Box b) {
cout << "Length is: " << b.length << endl; // Accessing private member
}

Explanation: The function showLength is able to access the private data member length of
the Box class.

c) Explain array of object in C++ with example.


An array of objects is used to store multiple objects of a class using a single array variable.

Example:

#include <iostream>
using namespace std;

class Student {
int roll;
public:
void setData(int r) { roll = r; }
void display() { cout << "Roll No: " << roll << endl; }
};

int main() {
Student s[3];
for(int i = 0; i < 3; i++) {
s[i].setData(i + 1);
}
for(int i = 0; i < 3; i++) {
s[i].display();
}
return 0;
}
Explanation: This creates an array s of 3 Student objects and initializes/display them using
loops.

d) Explain the different types of Inheritance with example.


C++ supports the following types of inheritance:

1. Single Inheritance: One base class and one derived class.


2. Multiple Inheritance: One derived class with multiple base classes.
3. Multilevel Inheritance: A class derived from a derived class.
4. Hierarchical Inheritance: Multiple derived classes from a single base class.
5. Hybrid Inheritance: A combination of more than one type of inheritance.

Example of Multilevel Inheritance:

#include <iostream>
using namespace std;

class A {
public:
void showA() { cout << "Class A\n"; }
};

class B : public A {
public:
void showB() { cout << "Class B\n"; }
};

class C : public B {
public:
void showC() { cout << "Class C\n"; }
};

Explanation: Class C inherits class B which in turn inherits class A.

e) List different types of constructor. Explain any one constructor with example.

Types of Constructors in C++:

1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Dynamic Constructor
5. Constructor Overloading

Example – Parameterized Constructor:

#include <iostream>
using namespace std;
class Rectangle {
int length, width;
public:
Rectangle(int l, int w) {
length = l;
width = w;
}
void display() {
cout << "Area: " << length * width << endl;
}
};

int main() {
Rectangle r(5, 3);
r.display();
return 0;
}

Explanation: The constructor takes parameters to initialize data members at the time of
object creation.

Q-3

a) Write a C++ program to find the maximum of two integer numbers using inline
function.

#include <iostream>
using namespace std;

inline int max(int a, int b) {


return (a > b) ? a : b;
}

int main() {
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
cout << "Maximum is: " << max(x, y) << endl;
return 0;
}

Explanation:
The max function is declared inline and returns the greater of two numbers using the ternary
operator.

b) Write a C++ program to find the area of circle and area of triangle using function
overloading.

#include <iostream>
using namespace std;
float area(float r) {
return 3.14 * r * r;
}

float area(float b, float h) {


return 0.5 * b * h;
}

int main() {
float radius, base, height;
cout << "Enter radius of circle: ";
cin >> radius;
cout << "Area of circle: " << area(radius) << endl;

cout << "Enter base and height of triangle: ";


cin >> base >> height;
cout << "Area of triangle: " << area(base, height) << endl;

return 0;
}

Explanation:
Two area functions are overloaded — one calculates circle area, the other triangle area based
on different parameters.

c) Write a C++ program to swap the values using call by reference method.

#include <iostream>
using namespace std;

void swap(int &a, int &b) {


int temp = a;
a = b;
b = temp;
}

int main() {
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
swap(x, y);
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
}

Explanation:
The swap function uses reference variables to swap values directly in memory.

d) Write a C++ program to create a class employee which contains data members as
e_id, e_name, e_Salary. Write member functions to accept and display employee
information, also display information of employee having maximum salary.
#include <iostream>
using namespace std;

class Employee {
int e_id;
string e_name;
float e_salary;

public:
void getData() {
cout << "Enter ID, Name, Salary: ";
cin >> e_id >> e_name >> e_salary;
}

void showData() {
cout << "ID: " << e_id << ", Name: " << e_name << ", Salary: " <<
e_salary << endl;
}

float getSalary() {
return e_salary;
}
};

int main() {
Employee e[3];
for(int i = 0; i < 3; i++) {
cout << "Enter details of employee " << i+1 << endl;
e[i].getData();
}

int maxIndex = 0;
for(int i = 1; i < 3; i++) {
if(e[i].getSalary() > e[maxIndex].getSalary()) {
maxIndex = i;
}
}

cout << "\nEmployee with highest salary:\n";


e[maxIndex].showData();
return 0;
}

Explanation:
This program uses an array of objects and identifies the employee with the maximum salary.

e) Write a C++ Program to overload unary ++ operator.

#include <iostream>
using namespace std;

class Counter {
int count;

public:
Counter() : count(0) {}
void operator++() {
++count;
}

void display() {
cout << "Count: " << count << endl;
}
};

int main() {
Counter c;
++c; // Unary operator overloading
c.display();
return 0;
}

Explanation:
The ++ operator is overloaded to increase the count variable when used with an object of
Counter.

Q-4

a) What is Template? Explain its types in detail.

Templates in C++ allow writing generic programs to work with any data type. It enables a
function or class to operate on different data types without rewriting code.

Types of Templates:

1. Function Template:
Used to create a generic function.
2. template <class T>
3. T add(T a, T b) {
4. return a + b;
5. }

6. Class Template:
Used to create a generic class.
7. template <class T>
8. class Box {
9. T value;
10. public:
11. void set(T v) { value = v; }
12. T get() { return value; }
13. };

Explanation: Templates promote code reuse and type safety by allowing operations on
various data types.
b) Explain file opening methods in C++ with syntax.

C++ provides file handling using fstream, ifstream, and ofstream classes. Files can be
opened in different modes:

Common file opening modes:

1. ios::in – Open for reading.


2. ios::out – Open for writing.
3. ios::app – Append mode.
4. ios::ate – Open and move to the end.
5. ios::binary – Open in binary mode.
6. ios::trunc – Truncate file if it exists.

Syntax:

ofstream fout("file.txt", ios::out);


ifstream fin("file.txt", ios::in);

Explanation:
You can combine modes using | operator, e.g., ios::out | ios::app.

c) Explain the types of polymorphism in detail.

Polymorphism allows a single interface to represent different data types or functions.

Types of Polymorphism in C++:

1. Compile-time (Static) Polymorphism:


Achieved using function overloading and operator overloading.
o Function Overloading: Multiple functions with the same name but different
parameters.
o Operator Overloading: Same operator behaves differently based on
operands.
2. Run-time (Dynamic) Polymorphism:
Achieved using virtual functions and inheritance.
o Base class defines a virtual function.
o Derived class overrides the function.
o Decision is made at runtime using pointers.

Example:

class Base {
public:
virtual void show() { cout << "Base\n"; }
};
class Derived : public Base {
public:
void show() { cout << "Derived\n"; }
};

d) Write a C++ program to calculate the Simple Interest. (Use default value for rate)

#include <iostream>
using namespace std;

float simpleInterest(float p, float t, float r = 5.0) {


return (p * t * r) / 100;
}

int main() {
float principal, time;
cout << "Enter Principal and Time: ";
cin >> principal >> time;

cout << "Simple Interest: " << simpleInterest(principal, time) << endl;
return 0;
}

Explanation:
The function uses a default argument r = 5.0 for the rate if not provided during the call.

e) What is the output of the following program?

#include <iostream.h>

void stat() {
int m = 0;
static int n = 0;
m++;
n++;
cout << m << " " << n << "\n";
}

void main() {
stat();
stat();
getch();
}

Output:

1 1
1 2

Explanation:

 m is a regular local variable: re-initialized to 0 on every call.


 n is a static variable: retains its value between function calls.
Q-5

a) Manipulators in C++

Manipulators are functions used to format output or input streams in C++. They are defined
in the <iomanip> and <iostream> header files.

Commonly Used Manipulators:

1. endl – Inserts a newline and flushes the output buffer.


2. setw(n) – Sets the width of the next input/output field to n spaces.
3. setprecision(n) – Sets the number of digits to display after the decimal point.
4. setfill(ch) – Fills the unused width with the specified character ch.
5. fixed and scientific – Set float output format.

Example:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
float num = 123.456;
cout << setw(10) << setfill('*') << fixed << setprecision(2) << num <<
endl;
return 0;
}

b) Exception Handling

Exception Handling in C++ is a mechanism to handle runtime errors and prevent program
crashes.

Keywords:

 try: Block where exceptions can occur.


 throw: Used to throw an exception.
 catch: Handles the thrown exception.

Syntax:

try {
// code that may throw exception
throw "Error!";
} catch (const char* msg) {
cout << "Caught: " << msg << endl;
}

Explanation:
 Code that may cause an error is placed inside try.
 If an error occurs, it is thrown using throw.
 catch handles the exception and prevents abnormal termination.

c) ‘this’ pointer

The this pointer is an implicit pointer available in all non-static member functions of a
class. It holds the address of the current calling object.

Uses of this pointer:

1. To resolve naming conflicts between member variables and parameters.


2. To return the object from a member function.
3. To pass the current object as a parameter.

Example:

class Sample {
int a;
public:
void setData(int a) {
this->a = a; // Resolves ambiguity
}
};

Explanation: In the example, this->a refers to the class member while a refers to the
parameter, resolving the conflict.

CPP PAPER-2

Q-1

a) List any four features of OOP's.

 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

b) Define pure virtual function.


A pure virtual function is a function with no definition in the base class and is declared using
= 0.
virtual void display() = 0;

c) What is cascading of I/O operator?


Cascading allows chaining of << or >> operators in a single statement.

cout << a << b << c;

d) List the ways to define a constant.

 Using const keyword


 Using #define preprocessor directive

e) What is an abstract class?


A class containing at least one pure virtual function is called an abstract class.

f) Define multiple inheritance.


When a class inherits from more than one base class, it is called multiple inheritance.

class C : public A, public B {};

g) Define destructor.
A destructor is a special member function that destroys an object. It has the same name as the
class prefixed with ~.

h) What is 'this' pointer?


this is an implicit pointer that holds the address of the current object.

i) What is Run-Time Polymorphism?


It is the ability to resolve function calls at runtime using virtual functions and base class
pointers.

j) Enlist manipulators in C++.

 endl
 setw()
 setprecision()
 setfill()
Q-2

a) Explain function overloading with example.

Function Overloading is a feature in C++ where two or more functions can have the same
name but different parameters (type or number).

Example:

#include <iostream>
using namespace std;

void display(int a) {
cout << "Integer: " << a << endl;
}

void display(float b) {
cout << "Float: " << b << endl;
}

int main() {
display(10);
display(5.5f);
return 0;
}

Explanation:
The compiler differentiates functions by their parameter list. It helps in increasing code
readability and reusability.

b) What is inheritance? Explain types of inheritance.

Inheritance is a mechanism in C++ where a class (derived class) inherits properties and
behaviors from another class (base class).

Types of Inheritance:

1. Single Inheritance:
One base and one derived class.
class B : public A {};
2. Multiple Inheritance:
One derived class inherits from multiple base classes.
class C : public A, public B {};
3. Multilevel Inheritance:
Derived from a derived class.
class B : public A {}; class C : public B {};
4. Hierarchical Inheritance:
Multiple derived classes from a single base class.
class B : public A {}; class C : public A {};
5. Hybrid Inheritance:
Combination of two or more types of inheritance.

Explanation:
Inheritance promotes code reuse and establishes a parent-child relationship between classes.

c) Explain static data members and static member functions


with example.

Static Data Member:

 Shared by all objects of the class.


 Declared with static keyword.
 Initialized outside the class.

Static Member Function:

 Can access only static members.


 Called using class name.

Example:

#include <iostream>
using namespace std;

class Test {
static int count;
public:
static void showCount() {
cout << "Count: " << count << endl;
}
};

int Test::count = 10;

int main() {
Test::showCount();
return 0;
}

Explanation:
Static members help in tracking values common across all objects, like counters or
configuration.
d) What is friend function? Write characteristics of friend
function.

A friend function is a non-member function that has access to private and protected
members of a class.

Syntax:

class A {
int x;
friend void show(A);
};

void show(A obj) {


cout << obj.x;
}

Characteristics:

1. Not in the scope of the class.


2. Cannot access members directly; needs object.
3. Declared inside the class with friend keyword.
4. Can be a friend to multiple classes.

Explanation:
Used when an external function needs to access private members without being a member
function.

e) Explain use of any four file opening modes.

1. ios::in
Opens file for reading.
Example: ifstream file("data.txt", ios::in);
2. ios::out
Opens file for writing (overwrites if exists).
Example: ofstream file("data.txt", ios::out);
3. ios::app
Opens file for appending data at the end.
Example: ofstream file("data.txt", ios::app);
4. ios::binary
Opens file in binary mode.
Example: ifstream file("data.dat", ios::binary);

Explanation:
These modes can be combined using | to customize file access as per the requirement.

Q-3
a) C++ program to create a class product and generate/display
bill
#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;
}

float getTotal() {
return price * quantity;
}

void display() {
cout << pname << "\t" << price << "\t" << quantity << "\t" <<
getTotal() << endl;
}
};

int main() {
int n;
cout << "Enter number of products: ";
cin >> n;

Product p[50];
float totalBill = 0;

for (int i = 0; i < n; i++) {


p[i].accept();
}

cout << "\nProduct\tPrice\tQty\tTotal\n";


for (int i = 0; i < n; i++) {
p[i].display();
totalBill += p[i].getTotal();
}

cout << "Total Bill: " << totalBill << endl;


return 0;
}

b) C++ program with person → employee → manager, find


highest salary
#include <iostream>
using namespace std;

class Person {
public:
string name, address;
long phoneno;
void acceptPerson() {
cout << "Enter Name, Address, Phone: ";
cin >> name >> address >> phoneno;
}
};

class Employee : public Person {


public:
int eno;
string ename;
void acceptEmployee() {
cout << "Enter Employee No and Name: ";
cin >> eno >> ename;
acceptPerson();
}
};

class Manager : public Employee {


public:
string designation, department;
float basic_salary;

void acceptManager() {
cout << "Enter Designation, Department, Basic Salary: ";
cin >> designation >> department >> basic_salary;
acceptEmployee();
}

void displayManager() {
cout << eno << "\t" << ename << "\t" << designation << "\t" <<
department << "\t" << basic_salary << endl;
}
};

int main() {
int n, index = 0;
cout << "Enter number of managers: ";
cin >> n;
Manager m[50];
float maxSalary = 0;

for (int i = 0; i < n; i++) {


m[i].acceptManager();
if (m[i].basic_salary > maxSalary) {
maxSalary = m[i].basic_salary;
index = i;
}
}

cout << "\nManager with Highest Salary:\n";


m[index].displayManager();

return 0;
}

c) C++ program to overload functions to calculate area


#include <iostream>
using namespace std;

float area(float radius) {


return 3.14 * radius * radius;
}

float area(float side, int flag) {


return side * side; // square
}

float area(float l, float b) {


return l * b; // rectangle
}

int main() {
cout << "Area of Circle: " << area(3.0f) << endl;
cout << "Area of Square: " << area(4.0f, 1) << endl;
cout << "Area of Rectangle: " << area(5.0f, 6.0f) << endl;
return 0;
}

d) C++ program to print pattern


#include <iostream>
using namespace std;

int main() {
char ch = 'A';
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
cout << ch << " ";
ch++;
}
cout << endl;
}
return 0;
}

Output:

A
B C
D E F
G H I J

e) C++ program to calculate perimeter using inline function


#include <iostream>
using namespace std;

inline float perimeter(float l, float w) {


return 2 * (l + w);
}

int main() {
float length, width;
cout << "Enter length and width of rectangle: ";
cin >> length >> width;
cout << "Perimeter: " << perimeter(length, width) << endl;
return 0;
}

Q-4

a) Trace output of the following program and explain it

Corrected Code:

#include <iostream.h>

class Number {
public:
int a, b;
static int cnt;

Number(int x, int y) {
cout << "\nConstructor called";
a = x;
b = y;
cnt++;
}

void display() {
cout << "\na = " << a << "\nb = " << b;
}
};

int Number::cnt;

void main() {
Number N1(4, 6), N2(2, 8);
cout << "\nTotal object created: " << Number::cnt;
}

Output:

Constructor called
Constructor called
Total object created: 2

Explanation:

 When N1 and N2 are created, the constructor is called twice.


 Each time, cnt (a static variable) is incremented.
 Hence, total object count is displayed as 2.
b) Explain parameterized constructor with the help of suitable
example

A parameterized constructor accepts arguments and initializes an object with specific


values.

Example:

class Box {
int length;
public:
Box(int l) { length = l; }
void show() { cout << "Length = " << length; }
};

Explanation:
When an object is created like Box b1(10);, the value 10 is passed to the constructor and
assigned to length.

c) Explain virtual base class with example

Virtual Base Class is used in multiple inheritance to avoid duplicate copies of base class
members in the inheritance chain.

Example:

class A {
public:
int x;
};

class B : virtual public A {};


class C : virtual public A {};
class D : public B, public C {};

int main() {
D obj;
obj.x = 5; // No ambiguity due to virtual inheritance
}

Explanation:
Without virtual, class D would have two copies of A::x. Virtual inheritance ensures only
one copy is shared.

d) Write a C++ program to find maximum of two integer


numbers using function template
#include <iostream>
using namespace std;
template <class T>
T maximum(T a, T b) {
return (a > b) ? a : b;
}

int main() {
int x = 10, y = 20;
cout << "Maximum: " << maximum(x, y);
return 0;
}

e) Write a program to overload binary plus operator to


concatenate two strings
#include <iostream>
#include <string.h>
using namespace std;

class String {
char str[100];
public:
void get() {
cout << "Enter string: ";
cin >> str;
}

String operator+(String s) {
String temp;
strcpy(temp.str, str);
strcat(temp.str, s.str);
return temp;
}

void display() {
cout << str << endl;
}
};

int main() {
String s1, s2, s3;
s1.get();
s2.get();
s3 = s1 + s2;
cout << "Concatenated String: ";
s3.display();
return 0;
}

Q-5

a) Array of Object

An array of objects is an array where each element is an object of a class. It is used to store
multiple objects of the same class type in a single array.
Example:

class Student {
public:
int roll_no;
void setRoll(int roll) {
roll_no = roll;
}
void display() {
cout << "Roll No: " << roll_no << endl;
}
};

int main() {
Student students[3]; // Array of 3 objects of class Student
students[0].setRoll(1);
students[1].setRoll(2);
students[2].setRoll(3);

for (int i = 0; i < 3; i++) {


students[i].display();
}
return 0;
}

Explanation:
An array of objects allows us to work with multiple objects of the same class without having
to declare each object individually.

b) Access Specifier

Access specifiers in C++ define the accessibility of class members (variables and functions)
from outside the class.

Types of Access Specifiers:

1. Public:
Members declared as public are accessible from outside the class.
2. class A {
3. public:
4. int x;
5. };

6. Private:
Members declared as private are only accessible within the class.
7. class A {
8. private:
9. int x;
10. };

11. Protected:
Members declared as protected are accessible within the class and by derived classes.
12. class A {
13. protected:
14. int x;
15. };

Explanation:
Access specifiers are important for data encapsulation, ensuring controlled access to the
internal data of a class.

c) Constructor in Derived Class

In C++, when a derived class object is created, the constructor of the base class is called first,
followed by the constructor of the derived class.

Example:

class Base {
public:
Base() {
cout << "Base class constructor called" << endl;
}
};

class Derived : public Base {


public:
Derived() {
cout << "Derived class constructor called" << endl;
}
};

int main() {
Derived d;
return 0;
}

Explanation:

1. Base class constructor is called automatically before the derived class constructor
when a derived class object is created.
2. If the base class has a parameterized constructor, it can be called explicitly from the
derived class constructor.

CPP PAPER-3

Q-1

a) What is Object Oriented Programming (OOP)?

Object Oriented Programming (OOP) is a programming paradigm based on the concept of


objects, which can contain data (attributes) and code (methods). OOP aims to improve
modularity, reusability, and scalability by using features like encapsulation, inheritance, and
polymorphism.
b) What are applications of C++?

C++ is widely used in areas requiring high performance and resource management, such as:

1. System Software (e.g., operating systems)


2. Game Development (e.g., graphics engines)
3. Embedded Systems (e.g., microcontroller programming)
4. Financial Applications (e.g., high-frequency trading)

c) Define the scope resolution operator in C++.

The scope resolution operator :: is used to define the scope of a function or variable. It is
used to access global variables or to define a function outside the class.

Example:

int x = 10;

class Test {
public:
static int x;
void display() {
cout << "Local x: " << x << endl;
cout << "Global x: " << ::x << endl;
}
};

d) List the memory management operators in C++.

Memory management operators in C++ are:

1. new: Allocates memory dynamically.


2. delete: Frees memory allocated using new.
3. new[]: Allocates memory for an array dynamically.
4. delete[]: Frees memory for an array allocated using new[].

e) Define inline functions.

Inline functions are functions defined with the inline keyword to suggest to the compiler
that the function's code should be inserted at the call site, reducing function call overhead.

Syntax:

inline int square(int x) {


return x * x;
}

f) What are default arguments in C++?

Default arguments allow functions to be called with fewer arguments than they are defined
with. Default values are assigned in the function declaration.

Example:

void display(int x = 5) {
cout << "Value: " << x << endl;
}

g) Define a class and an object in C++.

 Class: A blueprint for creating objects, defining methods and attributes.

Example:

class Car {
public:
string brand;
void display() {
cout << "Brand: " << brand << endl;
}
};

 Object: An instance of a class containing real values for the attributes.

Example:

Car myCar;
myCar.brand = "Toyota";
myCar.display();

h) List the access specifiers in C++.

C++ supports three access specifiers:

1. public: Members are accessible from outside the class.


2. private: Members are only accessible within the class.
3. protected: Members are accessible within the class and its derived classes.

i) What is the scope resolution operator in C++?

The scope resolution operator :: is used to access a global variable when a local variable
with the same name exists, or to define methods outside the class.
j) Define a destructor in C++ with its syntax.

A destructor is a special member function that is automatically called when an object is


destroyed. It is used to release resources or perform cleanup.

Syntax:

~ClassName() {
// Cleanup code
}

Example:

class Test {
public:
~Test() {
cout << "Destructor called" << endl;
}
};
Q-2

a) What are manipulators in C++? Give an example.

Manipulators in C++ are predefined functions used to format output in a more readable or
structured manner. They can be used to change the state of the stream (like setting the width
or precision) or manipulate the output in a particular format.

Common manipulators:

1. endl: Inserts a newline character and flushes the output buffer.


2. setw: Sets the width of the output field.
3. setprecision: Sets the number of digits to be displayed after the decimal point.
4. fixed: Used to display floating-point values in fixed-point notation.

Example:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
double num = 123.456789;
cout << "Default precision: " << num << endl;
cout << "Fixed precision (2 digits): " << fixed << setprecision(2) <<
num << endl;
cout << "Width set to 10: " << setw(10) << num << endl;
cout << "New line using endl" << endl;
return 0;
}
Output:

Default precision: 123.457


Fixed precision (2 digits): 123.46
Width set to 10: 123.457
New line using endl

b) Define reference variable in C++ and explain its use with an


example.

A reference variable in C++ is an alias or alternative name for an existing variable. It allows
you to access the original variable through a new name without creating a copy.

Syntax:

Type &referenceName = originalVariable;

Example:

#include <iostream>
using namespace std;

int main() {
int a = 10;
int &ref = a; // reference variable 'ref' refers to 'a'

cout << "a: " << a << endl; // Output: 10


cout << "ref: " << ref << endl; // Output: 10

ref = 20; // Changing 'ref' changes 'a'

cout << "a after modification: " << a << endl; // Output: 20
return 0;
}

Explanation:

 The reference variable ref is another name for the variable a.


 Modifying ref also modifies a because both refer to the same memory location.

c) Define Constructor. Explain any of its type along with


example.

A constructor is a special member function of a class that is automatically called when an


object of that class is created. It initializes the object's data members.

Types of Constructors:
1. Default Constructor: A constructor that takes no arguments and initializes the object
with default values.

Example:

class Box {
public:
int length;
Box() { // Default constructor
length = 10;
}
};

int main() {
Box b;
cout << "Length: " << b.length << endl; // Output: Length: 10
return 0;
}

2. Parameterized Constructor: A constructor that takes arguments to initialize an


object with specific values.

Example:

class Box {
public:
int length;
Box(int l) { // Parameterized constructor
length = l;
}
};

int main() {
Box b(20); // Initializes length with 20
cout << "Length: " << b.length << endl; // Output: Length: 20
return 0;
}

d) Define inheritance and its types in C++.

Inheritance is a mechanism in C++ that allows one class (derived class) to inherit properties
and behaviors (methods) from another class (base class). It promotes code reusability and
establishes a relationship between base and derived classes.

Types of Inheritance:

1. Single Inheritance: A class is derived from a single base class.


2. class Base { ... };
3. class Derived : public Base { ... };

4. Multiple Inheritance: A class is derived from more than one base class.
5. class Base1 { ... };
6. class Base2 { ... };
7. class Derived : public Base1, public Base2 { ... };
8. Multilevel Inheritance: A class is derived from another derived class.
9. class Base { ... };
10. class Derived1 : public Base { ... };
11. class Derived2 : public Derived1 { ... };

12. Hierarchical Inheritance: Multiple classes are derived from a single base class.
13. class Base { ... };
14. class Derived1 : public Base { ... };
15. class Derived2 : public Base { ... };

16. Hybrid Inheritance: A combination of more than one type of inheritance (e.g.,
multiple and multilevel inheritance).
17. class Base { ... };
18. class Derived1 : public Base { ... };
19. class Derived2 : public Derived1 { ... };

e) Explain operator overloading in C++ with an example.

Operator overloading allows a programmer to define or modify the behavior of operators


for user-defined data types (classes). It provides a way to perform operations on objects using
operators.

Example: Overloading the + operator for a Complex class:

#include <iostream>
using namespace std;

class Complex {
public:
int real, imag;

Complex(int r, int i) { real = r; imag = i; }

// Overloading the + operator


Complex operator+(Complex c) {
return Complex(real + c.real, imag + c.imag);
}

void display() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1(1, 2), c2(3, 4);
Complex c3 = c1 + c2; // Using overloaded + operator
c3.display(); // Output: 4 + 6i
return 0;
}

Explanation:

 The + operator is overloaded to allow the addition of two Complex objects.


 The operator+ function defines how two objects of Complex should be added,
returning a new Complex object.
Q-3

a) Explain the difference between a structure and a class in C+


+.

In C++, both structures and classes are used to define user-defined data types, but there are
key differences between them:

1. Default Access Specifiers:


o Structure: By default, members of a structure are public.
o Class: By default, members of a class are private.
2. Inheritance:
o Structure: In a structure, the default inheritance is public.
o Class: In a class, the default inheritance is private.
3. Usage:
o Structure: Structures are typically used for simple data grouping, where data
members are public.
o Class: Classes are used for more complex data manipulation and often involve
the use of member functions, encapsulation, and other object-oriented features.

Example:

// Structure
struct Student {
int id;
string name;
};

// Class
class StudentClass {
private:
int id;
string name;
public:
void setDetails(int id, string name) {
this->id = id;
this->name = name;
}
void display() {
cout << "ID: " << id << ", Name: " << name << endl;
}
};

b) Explain the use of a static data member and a static member


function in C++ with an example.

Static Data Member:


 A static data member is shared by all objects of a class, meaning all instances of the
class refer to the same memory location for that member. It is initialized only once.

Static Member Function:

 A static member function can access only static data members of a class and can be
called using the class name or an object. It cannot access non-static members.

Example:

#include <iostream>
using namespace std;

class Counter {
public:
static int count; // Static data member
Counter() {
count++;
}
static void displayCount() { // Static member function
cout << "Total count: " << count << endl;
}
};

int Counter::count = 0; // Initialize static data member

int main() {
Counter c1, c2;
Counter::displayCount(); // Access static function using class name
return 0;
}

Output:

Total count: 2

Explanation:

 count is a static data member, and it keeps track of the number of Counter objects
created.
 The static member function displayCount is used to print the count of objects.

c) Write a C++ program which defines a class named Bank


Account with two private data members balance and
interestRate. Implement a friend class named Bank with a
function named getInterest() that calculates and returns the
interest on the bank account using the interest rate.

Example:
#include <iostream>
using namespace std;

class BankAccount {
private:
double balance;
double interestRate;

public:
BankAccount(double b, double r) : balance(b), interestRate(r) {}

// Friend class declaration


friend class Bank;
};

class Bank {
public:
double getInterest(BankAccount &account) {
return (account.balance * account.interestRate) / 100;
}
};

int main() {
BankAccount account(1000, 5); // Balance: 1000, Interest Rate: 5%
Bank bank;
double interest = bank.getInterest(account);
cout << "Interest on the account: " << interest << endl;
return 0;
}

Output:

Interest on the account: 50

Explanation:

 BankAccount has private members balance and interestRate.


 The Bank class is declared as a friend of BankAccount, so it can accessthe private
members.
 The getInterest function in the Bank class calculates the interest based on the
balance and interest rate.

d) Explain the concept of virtual base class in C++ with an


example.

Virtual Base Class: A virtual base class is used in multiple inheritance to resolve the
problem of ambiguity caused by the presence of a common base class in multiple inheritance
hierarchies. It ensures that the base class is shared among derived classes, avoiding multiple
copies of the base class.

Example:

#include <iostream>
using namespace std;

class A {
public:
A() { cout << "Class A constructor" << endl; }
};

class B : virtual public A { // Virtual base class


public:
B() { cout << "Class B constructor" << endl; }
};

class C : virtual public A { // Virtual base class


public:
C() { cout << "Class C constructor" << endl; }
};

class D : public B, public C {


public:
D() { cout << "Class D constructor" << endl; }
};

int main() {
D obj; // Only one instance of A is created
return 0;
}

Output:

Class A constructor
Class B constructor
Class C constructor
Class D constructor

Explanation:

 By declaring class A as a virtual base class in both B and C, only one instance of A is
created when D is instantiated, resolving the ambiguity.

e) Explain the concept of objects as a function argument in C+


+.

In C++, objects can be passed to functions as arguments. There are three ways to pass objects
to functions:

1. Pass by Value: A copy of the object is passed to the function.


2. Pass by Reference: The actual object is passed, and any changes made to it will
affect the original object.
3. Pass by Pointer: A pointer to the object is passed.

Example:

#include <iostream>
using namespace std;

class Box {
public:
int length;
Box(int l) : length(l) {}
void display() {
cout << "Length: " << length << endl;
}
};

// Passing by value
void displayByValue(Box b) {
b.display();
}

// Passing by reference
void displayByReference(Box &b) {
b.display();
}

int main() {
Box box(10);

cout << "Passing by value: ";


displayByValue(box);

cout << "Passing by reference: ";


displayByReference(box);

return 0;
}

Output:

Passing by value: Length: 10


Passing by reference: Length: 10

Explanation:

 When passing by value, a copy of the object is made, and changes made to b inside
displayByValue won't affect the original object.
 When passing by reference, the function works with the original object, so any
changes made will affect the object outside the function.

Q-4
a) Write a C++ program to demonstrate function overloading
using the following functions:

i) int sum(int a, int b)


ii) float sum(float a, float b)
iii) int sum(int a, int b, int c)

Program:

#include <iostream>
using namespace std;

// Function to sum two integers


int sum(int a, int b) {
return a + b;
}

// Function to sum two floats


float sum(float a, float b) {
return a + b;
}

// Function to sum three integers


int sum(int a, int b, int c) {
return a + b + c;
}

int main() {
int x = 5, y = 10, z = 15;
float a = 3.5, b = 7.2;

cout << "Sum of integers: " << sum(x, y) << endl;


cout << "Sum of floats: " << sum(a, b) << endl;
cout << "Sum of three integers: " << sum(x, y, z) << endl;

return 0;
}

Output:

Sum of integers: 15
Sum of floats: 10.7
Sum of three integers: 30

Explanation:

 The program demonstrates function overloading, where multiple functions with the
same name sum are defined but with different parameters (number and type).
 The appropriate function is called based on the arguments passed during the function
call.
b) Write a class template named ‘Pair’ that can store a pair of
values of different data types. The class should have two
private data members, ‘first’ and ‘second’, and a constructor
that can initialize both data members. The class should also
have public member functions to get and set the values of the
data members.

Program:

#include <iostream>
using namespace std;

// Class template for storing a pair of values of different types


template <class T1, class T2>
class Pair {
private:
T1 first;
T2 second;

public:
// Constructor to initialize both data members
Pair(T1 a, T2 b) : first(a), second(b) {}

// Getter functions
T1 getFirst() { return first; }
T2 getSecond() { return second; }

// Setter functions
void setFirst(T1 a) { first = a; }
void setSecond(T2 b) { second = b; }
};

int main() {
Pair<int, string> p1(1, "One");
cout << "First: " << p1.getFirst() << ", Second: " << p1.getSecond() <<
endl;

p1.setFirst(2);
p1.setSecond("Two");
cout << "Updated First: " << p1.getFirst() << ", Updated Second: " <<
p1.getSecond() << endl;

return 0;
}

Output:

First: 1, Second: One


Updated First: 2, Updated Second: Two

Explanation:

 The class Pair is a template class that can store a pair of values of any data types
(using T1 and T2 as generic types).
 Getter and setter functions are used to access and modify the values of first and
second.

c) Write a C++ program to read data from a file named


“input.txt” and write the data to a new file named “output.txt”.
The program should remove any blank lines from the input file.

Program:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream inputFile("input.txt");
ofstream outputFile("output.txt");

string line;

// Check if files are open


if (!inputFile.is_open()) {
cout << "Unable to open input file." << endl;
return 1;
}
if (!outputFile.is_open()) {
cout << "Unable to open output file." << endl;
return 1;
}

// Read each line from input file


while (getline(inputFile, line)) {
if (!line.empty()) {
outputFile << line << endl; // Write non-blank lines to output
file
}
}

inputFile.close();
outputFile.close();
cout << "Data copied to output.txt without blank lines." << endl;

return 0;
}

Explanation:

 The program opens input.txt for reading and output.txt for writing.
 It reads each line from the input file, and if the line is not blank, it writes it to the
output file.
 Blank lines are skipped.
d) Create a class called “Shape” with a protected member
variable “color”. Add a public method called “getColor()” that
returns the value of “color”. Create two subclasses of “Shape”
called “Rectangle” and “Circle”. The “Rectangle” class should
have private member variables for “width” and “height” and a
public method called “getArea()” that returns the area of the
rectangle. The “Circle” class should have a private member
variable for “radius” and a public method called “getArea()”
that returns the area of the circle. Override the “getColor()”
method in both subclasses to return the color of the shape.

Program:

#include <iostream>
#include <cmath>
using namespace std;

class Shape {
protected:
string color;

public:
Shape(string c) : color(c) {}

virtual string getColor() { return color; } // Virtual function to be


overridden
virtual double getArea() = 0; // Pure virtual function for area
};

class Rectangle : public Shape {


private:
double width, height;

public:
Rectangle(string c, double w, double h) : Shape(c), width(w), height(h)
{}

string getColor() override { return color; }


double getArea() override { return width * height; }
};

class Circle : public Shape {


private:
double radius;

public:
Circle(string c, double r) : Shape(c), radius(r) {}

string getColor() override { return color; }


double getArea() override { return M_PI * radius * radius; }
};

int main() {
Rectangle rect("Red", 5.0, 10.0);
Circle circ("Blue", 7.0);

cout << "Rectangle Color: " << rect.getColor() << ", Area: " <<
rect.getArea() << endl;
cout << "Circle Color: " << circ.getColor() << ", Area: " <<
circ.getArea() << endl;

return 0;
}

Output:

Rectangle Color: Red, Area: 50


Circle Color: Blue, Area: 153.938

Explanation:

 The Shape class is the base class, and it has a virtual function getArea() and a virtual
function getColor() which are overridden in the derived classes Rectangle and
Circle.
 The getArea() function in each subclass calculates and returns the area of the
respective shape.

e) Trace the output of the following program and explain it.

Program:

#include <iostream>
using namespace std;

int add(int a, int b) {


return a + b;
}

float add(float a, int b) {


return a + b; // Error: extra comma in the return statement
}

int main() {
int x = 5, y = 10;
float a = 3.5, b = 7.2;

cout << "Sum of " << x << " and " << y << " is: " << add(x, y) << endl;
cout << "Sum of " << a << " and " << b << " is: " << add(a, b) << endl;

return 0;
}

Explanation:

 The program attempts to perform function overloading by defining two add()


functions with different parameter types.
 The first add() function works fine for two integer arguments.
 The second add() function has an error: an extra comma in the return statement
(return a + b,;). This will result in a compilation error.

Output:

 Compilation error because of the extra comma in the second add() function. The
program will not run until the error is fixed.

Q-5

a) Virtual Functions

Definition: A virtual function is a member function in a base class that is declared using the
virtual keyword and is meant to be overridden in derived classes. It is used to achieve
runtime polymorphism, which allows a function to behave differently based on the object
type at runtime.

Explanation: When a function is declared as virtual in a base class, it allows the derived
class to override that function. The function call is resolved at runtime based on the object
type, not the pointer type (which is the case with non-virtual functions). This mechanism
enables dynamic dispatch of function calls.

Syntax:

class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};

class Derived : public Base {


public:
void show() override { // Override base class function
cout << "Derived class show function" << endl;
}
};

Example:

#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived class show function" << endl;
}
};

int main() {
Base* bptr;
Derived d;
bptr = &d;

bptr->show(); // Calls Derived class show()

return 0;
}

Output:

Derived class show function

Explanation:

 The show() function is virtual, so the function call is resolved to the Derived class
version of the function, even though the pointer is of type Base*.
 This demonstrates runtime polymorphism enabled by virtual functions.

b) Exception Handling

Definition: Exception handling in C++ is a mechanism to handle runtime errors or


exceptional conditions in a program. It involves three key components: try, throw, and
catch. It helps in managing errors effectively without crashing the program.

Explanation:

 The try block contains the code that might throw an exception.
 The throw statement is used to signal an error when an exceptional condition occurs.
 The catch block handles the exception and defines how to respond to the error.

Syntax:

try {
// Code that might throw an exception
if (condition) {
throw exception; // Throw an exception
}
} catch (ExceptionType e) {
// Handling exception
cout << "Exception caught: " << e.what() << endl;
}

Example:
#include <iostream>
#include <stdexcept>
using namespace std;

int divide(int a, int b) {


if (b == 0) {
throw runtime_error("Division by zero error");
}
return a / b;
}

int main() {
try {
int result = divide(10, 0);
cout << "Result: " << result << endl;
} catch (const runtime_error& e) {
cout << "Exception caught: " << e.what() << endl;
}

return 0;
}

Output:

Exception caught: Division by zero error

Explanation:

 The divide() function throws a runtime_error if division by zero is attempted.


 The catch block catches this exception and prints the error message.

c) Friend Function

Definition: A friend function in C++ is a function that is not a member of a class but is
allowed to access the private and protected members of that class. It is declared using the
friend keyword inside the class definition.

Explanation:

 Friend functions can be regular functions or member functions of another class. They
do not have the this pointer because they are not invoked on an object directly.
 They are often used when two or more classes need to share private data.

Syntax:

class ClassName {
friend returnType functionName(); // Declaring a friend function
public:
private members;
};

returnType functionName() {
// Function body
}

Example:

#include <iostream>
using namespace std;

class Box {
private:
double length;

public:
Box(double l) : length(l) {}

// Declaring a friend function


friend double getLength(Box b);
};

// Friend function
double getLength(Box b) {
return b.length;
}

int main() {
Box b(10.5);
cout << "Length of the box: " << getLength(b) << endl;
return 0;
}

Output:

Length of the box: 10.5

Explanation:

 The getLength() function is a friend of the Box class and can access its private
members (like length).
 This demonstrates how a non-member function can access private data of a class
using friendship.

CPP PAPER-4

Q-1

a) Explain tellg() and tellp() with syntax.

tellg(): The tellg() function is used with input streams to get the current position of the
"get" pointer (the read pointer) in a file.

Syntax:

streampos tellg();
tellp(): The tellp() function is used with output streams to get the current position of the
"put" pointer (the write pointer) in a file.

Syntax:

streampos tellp();

Example:

#include <fstream>
using namespace std;

int main() {
ifstream inFile("test.txt");
cout << "Current read position: " << inFile.tellg() << endl;

ofstream outFile("test.txt");
cout << "Current write position: " << outFile.tellp() << endl;

return 0;
}

b) Explain any two manipulators.

1. endl: The endl manipulator is used to insert a newline character (\n) and flush the
output buffer.

Example:

cout << "Hello World" << endl;

2. setw(): The setw() manipulator sets the width of the next output. It pads the output to
the right by default if the value is smaller than the width.

Example:

cout << setw(10) << 45 << endl;

c) What is destructor?

A destructor is a special member function that is automatically called when an object goes
out of scope or is explicitly deleted. It is used to release resources acquired by the object
during its lifetime.

Syntax:

~ClassName() {
// Code to release resources
}

Example:
class MyClass {
public:
~MyClass() {
cout << "Destructor called" << endl;
}
};

d) What are the visibility labels used in C++?

The visibility labels in C++ are used to specify the access level of class members. They are:

1. public: Members are accessible from outside the class.


2. private: Members are only accessible within the class itself.
3. protected: Members are accessible within the class and its derived classes.

e) What is extraction and insertion operator?

 Extraction Operator (>>): Used to read input from streams. Example:


 cin >> x;

 Insertion Operator (<<): Used to send output to streams. Example:


 cout << "Hello World";

f) What is abstraction and Encapsulation?

1. Abstraction: The process of hiding the implementation details and showing only the
essential features to the user. It is achieved through abstract classes and interfaces.
2. Encapsulation: The technique of bundling the data (variables) and methods
(functions) that operate on the data into a single unit called a class. It helps protect the
data from outside interference.

g) What is default argument in function?

A default argument is a value provided in the function declaration which is used when the
caller does not provide that argument. Default arguments must be specified from right to left.

Syntax:

void func(int a, int b = 5) {


// Code
}

Example:

void print(int x, int y = 10) {


cout << x << " " << y << endl;
}

print(5); // Uses default value for y

h) Write any two uses of scope resolution operator.

1. Accessing Global Variable: The scope resolution operator can be used to access
global variables when there is a local variable with the same name.
2. int x = 10;
3. void func() {
4. int x = 5;
5. cout << ::x; // Access global x
6. }

7. Defining Class Member Outside the Class: It is used to define class members
outside the class definition.
8. class MyClass {
9. public:
10. void display();
11. };
12.
13. void MyClass::display() {
14. cout << "Hello";
15. }

i) What is static Polymorphism?

Static polymorphism (also known as compile-time polymorphism) is achieved through


function overloading and operator overloading. The function or operator to be invoked is
resolved at compile time.

Example:

class Print {
public:
void show(int i) {
cout << "Integer: " << i << endl;
}

void show(double d) {
cout << "Double: " << d << endl;
}
};

j) Explain structure of C++ program.

A typical C++ program consists of the following components:

1. Preprocessor Directives: These include #include and #define for including


libraries or defining constants.
2. Main Function: Every C++ program must have a main() function, which is the entry
point.
3. Functions: The program may contain multiple functions for modularity.
4. Classes/Objects: If object-oriented programming is used, classes and objects are
defined.

Example:

#include <iostream>
using namespace std;

class MyClass {
public:
void display() {
cout << "Hello World" << endl;
}
};

int main() {
MyClass obj;
obj.display();
return 0;
}
Q-2

a) Explain operator overloading in C++ with an example.

Operator Overloading in C++ allows the programmer to define the behavior of operators
(like +, -, *, etc.) for user-defined types (like classes). This helps in making the code more
intuitive and easier to read.

Syntax: To overload an operator, you define a function using the keyword operator
followed by the operator symbol.

Example: Here is an example that demonstrates overloading the + operator for a class
Complex that represents complex numbers.

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imag;

public:
Complex() : real(0), imag(0) {}

Complex(float r, float i) : real(r), imag(i) {}

// Overloading the '+' operator


Complex operator + (const Complex& c) {
return Complex(real + c.real, imag + c.imag);
}
void display() {
cout << "Real: " << real << ", Imaginary: " << imag << endl;
}
};

int main() {
Complex c1(3.5, 4.5), c2(1.5, 2.5);
Complex c3 = c1 + c2; // Using the overloaded + operator
c3.display();

return 0;
}

Output:

Real: 5, Imaginary: 7

Explanation:

 The + operator has been overloaded to perform addition of two complex numbers by
adding their real and imaginary parts.
 The operator + function returns a new Complex object containing the sum.

b) Explain memory allocation for objects with non-static data


member and static data member.

In C++, memory allocation for objects can be categorized into non-static and static data
members:

1. Non-static Data Members:


o Non-static members are allocated memory for each object of the class.
o Each instance of the class has its own copy of non-static data members.
o They are allocated in the heap (if dynamically allocated) or the stack (if
allocated locally).

Example:

class MyClass {
public:
int x; // Non-static member
};

2. Static Data Members:


o Static data members are shared by all objects of the class. Only one copy of
the static member is created, no matter how many objects are instantiated.
o Static data members are allocated in a special area of memory and are
initialized only once.

Example:
class MyClass {
public:
static int count; // Static member
};

int MyClass::count = 0; // Definition outside the class

Memory Allocation Example:

 For non-static members, each object of the class will have its own copy of the x
variable.
 For static members, there is only one count variable shared by all objects of the
class.

c) What is pure virtual function and explain with the help of


example program.

A pure virtual function is a function in a base class that has no implementation and must be
overridden in derived classes. It is declared by assigning 0 to the function declaration in the
base class.

Syntax:

virtual returnType functionName() = 0;

Explanation:

 A pure virtual function makes the class abstract, meaning it cannot be instantiated
directly.
 It forces derived classes to implement the function.

Example:

#include <iostream>
using namespace std;

class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};

class Circle : public Shape {


public:
void draw() {
cout << "Drawing a Circle" << endl;
}
};

class Square : public Shape {


public:
void draw() {
cout << "Drawing a Square" << endl;
}
};

int main() {
// Shape s; // Error: cannot instantiate an abstract class
Shape* shape;
Circle c;
Square s;

shape = &c;
shape->draw(); // Calls Circle's draw()

shape = &s;
shape->draw(); // Calls Square's draw()

return 0;
}

Output:

Drawing a Circle
Drawing a Square

Explanation:

 Shape is an abstract class because it contains a pure virtual function.


 Both Circle and Square override the draw() function, which is required to make
them concrete classes that can be instantiated.

d) Explain Dynamic constructor with suitable example.

A dynamic constructor is a constructor that allocates memory dynamically for the objects
created at runtime. This is useful when the size of the data members is not known at compile
time and must be determined during program execution.

Example:

#include <iostream>
using namespace std;

class Array {
private:
int* arr;
int size;

public:
// Constructor to allocate memory dynamically
Array(int n) {
size = n;
arr = new int[size]; // Dynamic memory allocation
cout << "Array of size " << size << " created." << endl;
}

void setValue(int index, int value) {


if (index < size) {
arr[index] = value;
}
}

void display() {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

// Destructor to free dynamically allocated memory


~Array() {
delete[] arr;
cout << "Array memory freed." << endl;
}
};

int main() {
Array a(5); // Create an array of size 5 dynamically
a.setValue(0, 10);
a.setValue(1, 20);
a.setValue(2, 30);
a.display();

return 0;
}

Output:

Array of size 5 created.


10 20 30 0 0
Array memory freed.

Explanation:

 The constructor dynamically allocates memory for the array based on the size passed
at runtime.
 The destructor ensures that the dynamically allocated memory is freed when the
object goes out of scope.

e) What is inheritance and explain the hierarchical inheritance.

Inheritance is a mechanism in C++ where one class (derived class) inherits properties and
behaviors (methods and attributes) from another class (base class). This promotes code
reusability and a natural relationship between classes.

Types of Inheritance:

 Single inheritance: A derived class inherits from one base class.


 Multiple inheritance: A derived class inherits from more than one base class.
 Multilevel inheritance: A derived class inherits from another derived class.
 Hierarchical inheritance: Multiple derived classes inherit from a single base class.

Hierarchical Inheritance is when multiple derived classes inherit from the same base class.

Example:

#include <iostream>
using namespace std;

class Vehicle {
public:
void displayInfo() {
cout << "This is a vehicle" << endl;
}
};

class Car : public Vehicle {


public:
void carDetails() {
cout << "This is a car" << endl;
}
};

class Bike : public Vehicle {


public:
void bikeDetails() {
cout << "This is a bike" << endl;
}
};

int main() {
Car c;
Bike b;

c.displayInfo();
c.carDetails();

b.displayInfo();
b.bikeDetails();

return 0;
}

Output:

This is a vehicle
This is a car
This is a vehicle
This is a bike

Explanation:

 The Vehicle class is the base class.


 The Car and Bike classes are derived from the Vehicle class, which demonstrates
hierarchical inheritance.

Q-3
a) C++ Program to swap two numbers using call by reference.
#include <iostream>
using namespace std;

class SwapNumbers {
public:
int num1, num2;

// Function to accept values


void accept() {
cout << "Enter two numbers: ";
cin >> num1 >> num2;
}

// Function to display values


void display() {
cout << "Number 1: " << num1 << ", Number 2: " << num2 << endl;
}

// Function to swap numbers using call by reference


void swapNumbers(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
};

int main() {
SwapNumbers sn;
sn.accept(); // Accept user input
cout << "Before swapping: ";
sn.display(); // Display numbers before swap

// Swap the numbers


sn.swapNumbers(sn.num1, sn.num2);

cout << "After swapping: ";


sn.display(); // Display numbers after swap

return 0;
}

Explanation:

 The swapNumbers function swaps the values of two integers using call by reference.

b) C++ Program to create a Customer class and display


customer with max salary.
#include <iostream>
#include <string>
using namespace std;

class Customer {
public:
int C_id;
string C_name;
float C_salary;

// Function to accept customer details


void accept() {
cout << "Enter Customer ID: ";
cin >> C_id;
cout << "Enter Customer Name: ";
cin.ignore(); // to ignore newline from previous input
getline(cin, C_name);
cout << "Enter Customer Salary: ";
cin >> C_salary;
}

// Function to display customer details


void display() {
cout << "Customer ID: " << C_id << "\nCustomer Name: " << C_name <<
"\nCustomer Salary: " << C_salary << endl;
}
};

int main() {
int n;
cout << "Enter number of customers: ";
cin >> n;

Customer customers[n];
for (int i = 0; i < n; i++) {
cout << "\nEnter details for Customer " << i + 1 << endl;
customers[i].accept();
}

float maxSalary = customers[0].C_salary;


int maxSalaryIndex = 0;

// Find the customer with the maximum salary


for (int i = 1; i < n; i++) {
if (customers[i].C_salary > maxSalary) {
maxSalary = customers[i].C_salary;
maxSalaryIndex = i;
}
}

cout << "\nCustomer with Maximum Salary: ";


customers[maxSalaryIndex].display(); // Display details of the
customer with max salary

return 0;
}

Explanation:

 The Customer class holds the details of customers.


 The program accepts details of n customers and displays the customer with the
maximum salary.
c) C++ Program to calculate factorial of an integer using inline
function.
#include <iostream>
using namespace std;

class Factorial {
public:
// Inline function to calculate factorial
inline int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
};

int main() {
Factorial f;
int num;

cout << "Enter a number to calculate factorial: ";


cin >> num;

cout << "Factorial of " << num << " is: " << f.factorial(num) << endl;

return 0;
}

Explanation:

 The factorial function is defined as inline to optimize performance.


 The program calculates the factorial of the entered number using recursion.

d) C++ Program to count the number of times count() is called


using static data member.
#include <iostream>
using namespace std;

class CountCalls {
public:
static int count; // Static data member to keep track of count

// Function to count the number of calls


void countCalls() {
count++; // Increment the count each time count() is called
cout << "Function count() called " << count << " times." << endl;
}
};

// Initialize the static member


int CountCalls::count = 0;

int main() {
CountCalls obj;
obj.countCalls(); // First call
obj.countCalls(); // Second call
obj.countCalls(); // Third call

return 0;
}

Explanation:

 The static member count keeps track of how many times the countCalls() function
is called.
 Each time the function is called, it increments the count.

e) C++ Program to copy contents of a text file into another text


file.
#include <iostream>
#include <fstream>
using namespace std;

int main() {
string line;
ifstream inputFile("input.txt");
ofstream outputFile("output.txt");

if (!inputFile) {
cout << "Error opening input file." << endl;
return 1;
}

if (!outputFile) {
cout << "Error opening output file." << endl;
return 1;
}

// Copy contents from input.txt to output.txt


while (getline(inputFile, line)) {
outputFile << line << endl;
}

cout << "Contents copied from input.txt to output.txt." << endl;

inputFile.close();
outputFile.close();

return 0;
}

Explanation:

 The program uses ifstream to read data from input.txt and ofstream to write data
to output.txt.
 It reads each line from the input file and writes it to the output file.
Q-4

a) Object as Function Arguments

In C++, we can pass objects to functions as arguments. An object is passed either by value or
by reference. When passed by reference, the function works directly with the original object,
and any changes made within the function affect the original object.

Example Program:

#include <iostream>
using namespace std;

class Box {
public:
int length, breadth, height;

// Constructor to initialize dimensions


Box(int l, int b, int h) : length(l), breadth(b), height(h) {}

// Function to display box dimensions


void display() {
cout << "Length: " << length << ", Breadth: " << breadth << ",
Height: " << height << endl;
}
};

// Function that accepts an object by reference


void modifyBox(Box &b) {
b.length += 5;
b.breadth += 3;
b.height += 2;
}

int main() {
Box box1(10, 20, 30);

cout << "Before modifying: ";


box1.display();

// Passing object to function


modifyBox(box1);

cout << "After modifying: ";


box1.display();

return 0;
}

Explanation:

 The modifyBox function takes a reference to a Box object, modifies its data members,
and the changes reflect in the original object in main().
b) Characteristics of Friend Function

A friend function in C++ is a function that is not a member of a class but has access to its
private and protected members. It is declared inside the class using the friend keyword.

Characteristics of Friend Function:

1. Access to Private Members: A friend function can access the private and protected
data members of a class.
2. Not a Member: It is not a member of the class, meaning it is not invoked through an
object of the class.
3. Declaration: It is declared using the friend keyword inside the class definition.
4. Function Type: It can be a normal function, a method of another class, or even an
operator function.

Example:

#include <iostream>
using namespace std;

class Box {
private:
int length;
public:
Box(int l) : length(l) {}

// Friend function declaration


friend void displayLength(Box b);
};

// Friend function definition


void displayLength(Box b) {
cout << "Length of box: " << b.length << endl;
}

int main() {
Box box(10);
displayLength(box); // Accessing private member through friend
function
return 0;
}

Explanation:

 displayLength is a friend function of Box class, and it can access the private member
length of Box objects.

c) Class Template

A class template allows us to create a class that can work with any data type. The template is
like a blueprint for the class. It allows the definition of the class without specifying a
particular data type.
Syntax of Class Template:

template <class T>


class ClassName {
private:
T data; // data member of type T
public:
void setData(T val) { data = val; }
T getData() { return data; }
};

Example:

#include <iostream>
using namespace std;

template <class T>


class Box {
private:
T length;
public:
Box(T len) : length(len) {}
T getLength() { return length; }
};

int main() {
Box<int> intBox(10); // Integer Box
Box<float> floatBox(5.5); // Float Box

cout << "Length of integer box: " << intBox.getLength() << endl;
cout << "Length of float box: " << floatBox.getLength() << endl;

return 0;
}

Explanation:

 The Box class is templated, allowing us to create Box objects for any data type (int,
float, etc.).

d) Overloading Binary + Operator to Add Two Strings

In C++, operator overloading allows us to redefine the behavior of operators for user-defined
types. Here's how we can overload the + operator to concatenate two strings.

Example Program:

#include <iostream>
#include <string>
using namespace std;

class String {
private:
string str;
public:
String(string s) : str(s) {}

// Overload the binary '+' operator to concatenate two strings


String operator+(const String &other) {
return String(str + other.str);
}

void display() {
cout << "String: " << str << endl;
}
};

int main() {
String str1("Hello, ");
String str2("World!");

// Concatenate using overloaded '+' operator


String result = str1 + str2;

result.display(); // Output: Hello, World!

return 0;
}

Explanation:

 The + operator is overloaded to concatenate two String objects by combining their


str data members.

e) Trace the output of the following program.

Program:

#include <iostream.h>

class Point {
private:
int x;
int y;

public:
Point(int i, int j) {
x = i;
y = j;
cout << "constructor called";
}
};

int main() {
Point p1(1, 2), p2(3, 4);
return 0;
}

Explanation:
1. Constructor Call: When Point p1(1, 2) is created, the constructor is called and
"constructor called" is printed.
2. Then, when Point p2(3, 4) is created, the constructor is called again, and
"constructor called" is printed.

Output:

constructor called
constructor called

Explanation:

 The constructor is called twice: once for each object p1 and p2 in the main function.

Q-5

a) This Pointer

The this pointer in C++ is an implicit pointer that points to the current object of a class. It is
used within non-static member functions to refer to the calling object.

Characteristics:

1. Automatic Pointer: It is automatically passed to non-static member functions.


2. Non-Static Context: It can only be used in non-static member functions because
static member functions don't have a specific object associated with them.
3. Const Pointer: The this pointer is a constant pointer, meaning it cannot point to a
different object once initialized.
4. Return Value: It can be used to return the current object from a member function.

Example:

#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box(int len) : length(len) {}

// This pointer example


void display() {
cout << "Length of box: " << this->length << endl;
}
};

int main() {
Box box(10);
box.display(); // Outputs: Length of box: 10
return 0;
}
Explanation:

 In the display() function, this->length refers to the length member of the current
object.

b) Function Overriding

Function Overriding in C++ is a concept where a derived class redefines a function that is
already defined in its base class. This allows the derived class to provide its specific
implementation of the function.

Characteristics:

1. Same Function Signature: The overridden function must have the same name, return
type, and parameters as the function in the base class.
2. Virtual Function: The base class function must be declared as virtual to ensure
proper dynamic dispatch of the overridden function.
3. Runtime Polymorphism: Function overriding enables runtime polymorphism, where
the correct function is called based on the object type (base or derived).

Example:

#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};

class Derived : public Base {


public:
void show() override {
cout << "Derived class show function" << endl;
}
};

int main() {
Base* basePtr;
Derived derivedObj;

basePtr = &derivedObj;
basePtr->show(); // Output: Derived class show function

return 0;
}

Explanation:
 The show() function is overridden in the Derived class. The Base class function is
virtual, so at runtime, the function from the Derived class is called even though the
pointer is of type Base.

c) Exception Handling

Exception Handling in C++ is a mechanism to handle runtime errors or exceptional


situations, like invalid input or memory allocation failures. It ensures that the program does
not crash and provides a way to handle errors gracefully.

Key Components:

1. Try Block: Code that may throw an exception is enclosed in a try block.
2. Throw Statement: When an exception occurs, it is thrown using the throw keyword.
3. Catch Block: After throwing an exception, the catch block catches and handles it.

Syntax:

try {
// Code that may throw an exception
}
catch (ExceptionType e) {
// Handle exception
}

Example:

#include <iostream>
using namespace std;

void divide(int a, int b) {


if (b == 0) {
throw "Division by zero error!";
}
cout << "Result: " << a / b << endl;
}

int main() {
try {
divide(10, 0); // This will throw an exception
}
catch (const char* msg) {
cout << "Error: " << msg << endl; // Output: Error: Division by
zero error!
}

return 0;
}

Explanation:
 The divide() function checks for division by zero and throws an exception if b is
zero. The exception is caught and handled in the catch block, preventing the program
from crashing.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy