Cpp Paper Solutions
Cpp Paper Solutions
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.
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.
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++.
Q-2
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:
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.
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.
#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"; }
};
e) List different types of constructor. Explain any one constructor with example.
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
4. Dynamic Constructor
5. Constructor Overloading
#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;
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;
}
int main() {
float radius, base, height;
cout << "Enter radius of circle: ";
cin >> radius;
cout << "Area of circle: " << area(radius) << 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;
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;
}
}
Explanation:
This program uses an array of objects and identifies the employee with the maximum salary.
#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
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:
Syntax:
Explanation:
You can combine modes using | operator, e.g., ios::out | ios::app.
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;
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.
#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:
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.
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:
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.
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
Encapsulation
Inheritance
Polymorphism
Abstraction
g) Define destructor.
A destructor is a special member function that destroys an object. It has the same name as the
class prefixed with ~.
endl
setw()
setprecision()
setfill()
Q-2
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.
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.
Example:
#include <iostream>
using namespace std;
class Test {
static int count;
public:
static void showCount() {
cout << "Count: " << count << endl;
}
};
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);
};
Characteristics:
Explanation:
Used when an external function needs to access private members without being a member
function.
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;
class Person {
public:
string name, address;
long phoneno;
void acceptPerson() {
cout << "Enter Name, Address, Phone: ";
cin >> name >> address >> phoneno;
}
};
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;
return 0;
}
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;
}
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
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
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:
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.
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;
};
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.
int main() {
int x = 10, y = 20;
cout << "Maximum: " << maximum(x, y);
return 0;
}
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);
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.
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.
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;
}
};
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
C++ is widely used in areas requiring high performance and resource management, such as:
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;
}
};
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:
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;
}
Example:
class Car {
public:
string brand;
void display() {
cout << "Brand: " << brand << endl;
}
};
Example:
Car myCar;
myCar.brand = "Toyota";
myCar.display();
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.
Syntax:
~ClassName() {
// Cleanup code
}
Example:
class Test {
public:
~Test() {
cout << "Destructor called" << endl;
}
};
Q-2
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:
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:
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:
Example:
#include <iostream>
using namespace std;
int main() {
int a = 10;
int &ref = a; // reference variable 'ref' refers to 'a'
cout << "a after modification: " << a << endl; // Output: 20
return 0;
}
Explanation:
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;
}
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;
}
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:
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 { ... };
#include <iostream>
using namespace std;
class Complex {
public:
int real, 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:
In C++, both structures and classes are used to define user-defined data types, but there are
key differences between them:
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;
}
};
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 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.
Example:
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
double interestRate;
public:
BankAccount(double b, double r) : balance(b), interestRate(r) {}
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:
Explanation:
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; }
};
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.
In C++, objects can be passed to functions as arguments. There are three ways to pass objects
to functions:
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);
return 0;
}
Output:
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:
Program:
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 10, z = 15;
float a = 3.5, b = 7.2;
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;
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:
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.
Program:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inputFile("input.txt");
ofstream outputFile("output.txt");
string line;
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) {}
public:
Rectangle(string c, double w, double h) : Shape(c), width(w), height(h)
{}
public:
Circle(string c, double r) : Shape(c), radius(r) {}
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:
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.
Program:
#include <iostream>
using namespace std;
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:
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;
}
};
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;
return 0;
}
Output:
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
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 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:
Explanation:
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) {}
// 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:
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
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;
}
1. endl: The endl manipulator is used to insert a newline character (\n) and flush the
output buffer.
Example:
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:
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;
}
};
The visibility labels in C++ are used to specify the access level of class members. They are:
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.
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:
Example:
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. }
Example:
class Print {
public:
void show(int i) {
cout << "Integer: " << i << endl;
}
void show(double d) {
cout << "Double: " << d << endl;
}
};
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
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) {}
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.
In C++, memory allocation for objects can be categorized into non-static and static data
members:
Example:
class MyClass {
public:
int x; // Non-static member
};
Example:
class MyClass {
public:
static int count; // Static member
};
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.
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:
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
};
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:
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 display() {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << 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:
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.
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:
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;
}
};
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:
Q-3
a) C++ Program to swap two numbers using call by reference.
#include <iostream>
using namespace std;
class SwapNumbers {
public:
int num1, num2;
int main() {
SwapNumbers sn;
sn.accept(); // Accept user input
cout << "Before swapping: ";
sn.display(); // Display numbers before swap
return 0;
}
Explanation:
The swapNumbers function swaps the values of two integers using call by reference.
class Customer {
public:
int C_id;
string C_name;
float C_salary;
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();
}
return 0;
}
Explanation:
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 << "Factorial of " << num << " is: " << f.factorial(num) << endl;
return 0;
}
Explanation:
class CountCalls {
public:
static int count; // Static data member to keep track of count
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.
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;
}
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
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;
int main() {
Box box1(10, 20, 30);
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.
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) {}
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:
Example:
#include <iostream>
using namespace std;
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.).
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) {}
void display() {
cout << "String: " << str << endl;
}
};
int main() {
String str1("Hello, ");
String str2("World!");
return 0;
}
Explanation:
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:
Example:
#include <iostream>
using namespace std;
class Box {
private:
int length;
public:
Box(int len) : length(len) {}
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;
}
};
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
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;
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.