0% found this document useful (0 votes)
35 views99 pages

Oops Answer

OOPS Question

Uploaded by

balamurgan406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views99 pages

Oops Answer

OOPS Question

Uploaded by

balamurgan406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

14a) What is function overloading?

Explain the types of function overloading with respect


to the number of arguments and data type of arguments using example programs.

Function Overloading:

when there are multiple functions with the same name but different parameter lists.then
the functions are set to be overloaded.This is known as function overloading

function can be overloaded by changing the number of arguments or changing the type of
arguments.

functions having same name but distinct parameter when numerous tasks are listed under
one name.

EXAMPLE:

///Function overloading for area calculation

#include <iostream>

using namespace std;

class ShapeCalculator {

public:

// Function to calculate and print area of a square

void printArea(double side) {

double area = side * side;

cout << "Area of square with side " << side << " is: " << area << endl;

// Function to calculate and print area of a rectangle

void printArea(double length, double width) {


double area = length * width;

cout << "Area of rectangle with length " << length

<< " and width " << width << " is: " << area << endl;

};

int main() {

ShapeCalculator calculator;

// Calculate and print area of a square

calculator.printArea(5.0);

// Calculate and print area of a rectangle

calculator.printArea(4.0, 6.0);

return 0;

Output:

Area of square with side 5 is: 25

Area of rectangle with length 4 and width 6 is: 24

Explanation:

• The printArea function is overloaded based on the number of arguments it


accepts.
• The compiler determines which version of the function to call based on the number
of arguments passed during the function call.
• In the main function, the first printArea call uses a single argument, so the version
that takes a single double argument is used to calculate the area of the square.
• The second printArea call uses two arguments, so the version that takes two
double arguments is used to calculate the area of the rectangle.

Types of Function Overloading

1. Overloading Based on Number of Arguments:

This type of function overloading occurs when multiple functions have the same name but
differ in the number of arguments they accept. This allows you to create functions that
perform a similar task but handle different scenarios based on the input data.

EXAMPLE:
#include <iostream>

using namespace std;

void greet() {

cout << "Hello!" << endl;

void greet(string name) {

cout << "Hello, " << name << "!" << endl;

int main() {

greet(); // Calls greet() with no arguments

greet("Alice"); // Calls greet(string) with one argument


return 0;

Output:

Hello!

Hello, Alice!

Explanation:

• Two greet functions:


o The first greet function takes no arguments and prints a general greeting.
o The second greet function takes a string argument (the name) and prints a
personalized greeting.
• Function calls:
o The first greet() call invokes the function with no arguments, resulting in
the output "Hello!".
o The second greet("Alice") call passes the string "Alice" as an argument,
causing the function with the string parameter to be called, resulting in the
output "Hello, Alice!".

Function Overloading Based on Data Type of Arguments

This type of function overloading occurs when multiple functions have the same name but
differ in the data types of the arguments they accept. This allows you to create functions
that perform a similar task but handle different data types.

EXAMPLE:
#include <iostream>

using namespace std;

int add(int a, int b) {

return a + b;
}

double add(double a, double b) {

return a + b;

int main() {

int result1 = add(5, 3);

double result2 = add(2.5, 3.7);

cout << "Result 1: " << result1 << endl;

cout << "Result 2: " << result2 << endl;

return 0;

Output:

Result 1: 8
Result 2: 6.2

Explanation:

• Two add functions:


o The first add function takes two integer arguments and returns their sum as
an integer.
o The second add function takes two double arguments and returns their sum
as a double.
• Function calls:
o The first add(5, 3) call passes integer arguments, resulting in the integer
addition and the result is stored in result1.
o The second add(2.5, 3.7) call passes double arguments, resulting in the
double addition and the result is stored in result2.

14b) How will you overload binary operators using friend functions? Explain with
examples.

Friend Functions and Binary Operator Overloading

• Binary Operator Overloading

Binary operators, such as +, -, *, /, %, <<, >>, &, |, and ^, are used to perform
operations on two operands. In C++, you can redefine the behavior of these
operators for custom data types through operator overloading. This allows you to
create more intuitive and natural syntax for working with your custom objects.

• Friend Functions: These are functions that have access to the private members of
a class. They are declared as friend within the class definition.
Syntax:
Return_Type classname :: operator op(Argument list)
{
Function Body
} // This can be done by declaring the function

Here,

• Return_Type is the value type to be returned to another object.


• operator op is the function where the operator is a keyword.
• op is the operator to be overloaded

Steps to Overload a Binary Operator Using a Friend Function:

2. Declare the Friend Function:


o Inside the class definition, declare the friend function using the friend
keyword. The function should take the class object as an argument.
3. Define the Friend Function:
o Outside the class definition, define the friend function. Implement the
desired logic for the operator.
4. Use the Overloaded Operator:
o Create objects of the class and use the overloaded operator with them.

Example: Overloading the +,* operator for a Complex class

#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
Complex(double r = 0, double i = 0) {
real=r;
imag=i;
}
void display() {
cout << real;
if (imag >= 0) {
cout << " + " << imag << "i";
}
else{
cout << " - " << -imag << "i";
}
}
friend Complex operator+(Complex c1, Complex c2);

friend Complex operator*(Complex c1,Complex c2);


};

// Implementation of operator+ overload


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

// Implementation of operator* overload


Complex operator*(Complex c1,Complex c2 ) {
return Complex(c1.real * c2.real - c1.imag * c2.imag,
c1.real * c2.imag + c1.imag * c2.real);
}

int main() {
Complex c1(3, 2);
Complex c2(1, 4);

Complex sum = c1 + c2;


Complex product = c1 * c2;

cout << "c1 + c2 = " << sum.display() << endl;


cout << "c1 * c2 = " << product.display()<< endl;

return 0;
}
Output:
c1 + c2 = 4+6i
c1 * c2 = -5+14i
Detailed Explanation:
Class Definition:
• Complex class: Represents complex numbers.
• real and imag private members: Store the real and imaginary parts of the complex
number, respectively.
• Complex(double r = 0, double i = 0) constructor: Initializes a Complex
object with the specified real and imaginary parts.
• Friend functions:
o operator+: Overloads the addition operator for complex numbers.
o operator*: Overloads the multiplication operator for complex numbers.

Operator Overloads:

• operator+: Adds the real and imaginary parts of two complex numbers and returns
a new Complex object.
• operator*: Multiplies two complex numbers using the standard formula for
complex multiplication.
Main Function:

• Creates two Complex objects, c1 and c2, with initial values.


• Performs addition and multiplication using the overloaded operators.
• Prints the results
Explanation:
• The code defines a Complex class to represent complex numbers.
• The operator+ and operator* functions are overloaded to perform addition and
multiplication of complex numbers, respectively.
• The operator<< function is overloaded to print complex numbers in a readable
format.
• In the main function, c1 and c2 are created with initial values.
• The + and * operators are used to add and multiply the complex numbers, and the
results are stored in sum and product, respectively.

By using friend functions for operator overloading, you can create more readable, flexible,
and maintainable code, making it easier to work with custom data types and perform
operations on them.

15a) Create a base class Shape with relevant data members and member functions to
get data and print the area. Create two more classes Rectangle and Triangle which inherit
Shape class. Make the print data function as virtual function in base class. Write a C++
main ( ) function to check this.

#include <iostream>

using namespace std;

class Shape {

public:

virtual void printData() = 0;

virtual double getArea() = 0;


};

class Rectangle : public Shape {

private:

double length, breadth;

public:

Rectangle(double l, double b) : length(l), breadth(b) {}

void printData() override {

cout << "Rectangle: Length = " << length << ", Breadth = " << breadth << endl;

double getArea() override {

return length * breadth;

};

class Triangle : public Shape {

private:

double base, height;


public:

Triangle(double b, double h) : base(b), height(h) {}

void printData() override {

cout << "Triangle: Base = " << base << ", Height = " << height << endl;

double getArea() override {

return 0.5 * base * height;

};

int main() {

Rectangle rect(5, 3);

Triangle tri(4, 6);

rect.printData();

cout << "Area: " << rect.getArea() << endl;

tri.printData();

cout << "Area: " << tri.getArea() << endl;


return 0;

Output:

rectangle:

Length = 5, Breadth = 3

Area: 15

Triangle:

Base = 4, Height = 6

Area: 12

15b) Create three classes Employee, Boss and CEO. Employee class stores basic details
like, name, employee no, department. The Boss class gets the salary and calculates the
bonus as 10% of the salary. The CEO class contains shares details that the employee
owns. An employee is allowed to own a share only if the salary exceeds 50,000. Include
Info ( ) and writeInfo( ) functions in all the classes. Use the inheritance concept and display
the employee details with bonus and shares eligibility.

#include <iostream>

#include <string>

using namespace std;

// Base class Employee

class Employee {

protected:
string name;

int empNo;

string department;

public:

void getInfo() {

cout << "Enter name, employee number, and department: ";

cin >> name >> empNo;

getline(cin, department); // Consume newline left in input buffer

cout << "Enter department (again, to avoid formatting issues): ";

getline(cin, department);

void writeInfo() {

cout << "Name: " << name << endl;

cout << "Employee Number: " << empNo << endl;

cout << "Department: " << department << endl;

};

// Derived class Boss

class Boss : public Employee {

protected:
double salary;

double bonus;

public:

void getInfo() {

Employee::getInfo();

cout << "Enter salary: ";

cin >> salary;

calculateBonus();

void writeInfo() {

Employee::writeInfo();

cout << "Salary: " << salary << endl;

cout << "Bonus: " << bonus << endl;

void calculateBonus() {

bonus = salary * 0.10;

};

// Derived class CEO


class CEO : public Boss {

private:

int shares;

public:

void getInfo() {

Boss::getInfo();

if (salary > 50000) {

cout << "Enter number of shares: ";

cin >> shares;

} else {

cout << "Not eligible for shares." << endl;

shares = 0;

void writeInfo() {

Boss::writeInfo();

if (shares > 0) {

cout << "Shares: " << shares << endl;

} else {

cout << "Not eligible for shares." << endl;

}
}

};

int main() {

CEO ceo;

ceo.getInfo();

cout << "\nEmployee Details:" << endl;

ceo.writeInfo();

return 0;

SAMPLE INPUT:

Enter name, employee number, and department: john 67 sales

Enter salary: 90000

Enter number of shares: 4

Employee Details:

Name: john

Employee Number: 67

Department: sales

Salary: 90000

Bonus: 9000

Shares: 4
mini

16a) Write C++ programs for handling all types of exceptions .Explain about each type of
exception with separate program for each type.

1.TRY AND CATCH BLOCK EXECPTION

#include <iostream>

using namespace std;

int main() {

int a, b;

try {

cout << "Enter two numbers: ";

cin >> a >> b;

if (b == 0) {

throw runtime_error("Division by zero is not allowed.");

int result = a / b;

cout << "Result: " << result << endl;

} catch (const runtime_error& e) {


cerr << "Error: " << e.what() << endl;

return 0;

OUTPUT

Enter two numbers: 9

ERROR!

Error: Division by zero is not allowed.

2. Logic Failure Exceptions:

C++
• #include <iostream>
#include <stdexcept>

using namespace std;

int main() {
int a, b;

try {
cout << "Enter two numbers: ";
cin >> a >> b;

if (b == 0) {
throw logic_error("Division by zero is not
allowed.");
}
int result = a / b;
cout << "Result: " << result << endl;
} catch (const logic_error& e) {
cerr << "Logic error: " << e.what() << endl;
}

return 0;
}
Explanation: This program demonstrates how to handle logic failure exceptions,
specifically division by zero. It uses a try-catch block to catch the logic_error
exception and print an appropriate error message.
OUTPUT:
Enter two numbers: 10 0
Logic error: Division by zero is not allowed.

3. Runtime Error Exceptions:

C++
• #include <iostream>
#include <stdexcept>

using namespace std;

int main() {
int arr[] = {1, 2, 3};
int index;

try {
cout << "Enter an index: ";
cin >> index;

if (index < 0 || index >= 3) {


throw runtime_error("Index out of bounds.");
}

cout << "Element at index " << index << ": " <<
arr[index] << endl;
} catch (const runtime_error& e) {
cerr << "Runtime error: " << e.what() << endl;
}

return 0;
}
OUTPUT:
Enter an index:
3 Runtime error: Index out of bounds.
Explanation: This program handles runtime error exceptions by checking if the
input index is within the valid range of an array. If it is not, a runtime_error
exception is thrown and caught, providing a suitable error message.

4. Bad Exception Exceptions:

C++
• #include <iostream>
#include <stdexcept>

using namespace std;

int main() {
try {
throw bad_exception();
} catch (const bad_exception& e) {
cerr << "Bad exception: " << e.what() << endl;
}

return 0;
}
• OUTPUT;
Bad exception: Unexpected exception.
Explanation: This program demonstrates how to handle bad_exception
exceptions, which are typically thrown when an unexpected exception occurs. It
catches the bad_exception and prints its message.

5. Bad Cast Exceptions:

C++
#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
int x = 10;
double* p = reinterpret_cast<double*>(&x);

try {
double y = *p;
cout << "y: " << y << endl;
} catch (const bad_cast& e) {
cerr << "Bad cast: " << e.what() << endl;
}

return 0;
}
OUTPUT:
Bad cast: Invalid pointer cast.
• Explanation: This program handles bad_cast exceptions that occur when an
invalid type conversion is attempted. It casts an integer pointer to a double pointer,
which is invalid, and catches the bad_cast exception.

6. Bad Typeid Exceptions:

C++
• #include <iostream>
#include <stdexcept>
#include <typeinfo>

using namespace std;

int main() {
int x = 10;
double* p = reinterpret_cast<double*>(&x);

try {
typeid(*p).name();
} catch (const bad_typeid& e) {
cerr << "Bad typeid: " << e.what() << endl;
}

return 0;
}
OUTPUT:
Bad cast: Invalid pointer cast.
Explanation: This program handles bad_typeid exceptions that occur when the
typeid operator is used on an invalid type. It attempts to get the type information of
a pointer that points to an incorrect type, and catches the bad_typeid exception.

7 Bad Alloc Exceptions:

C++
#include <iostream>
#include <stdexcept>
#include <new>

using namespace std;

int main() {
try {
int* p = new int[1000000000]; // Allocate a large amount of
memory
delete[] p;
} catch (const bad_alloc& e) {
cerr << "Bad alloc: " << e.what() << endl;
}

return 0;
}
OUTPUT:
Bad alloc: Memory allocation failed.
• Explanation: This program handles bad_alloc exceptions that occur when
memory allocation fails. It attempts to allocate a large amount of memory, which
may exceed the available memory, and catches the bad_alloc exception.

16b) Write a function template for finding the minimum value contained in an array.
Explain the working of function templates in detail.

template <typename T>


T findMin(const T arr[], int size) {

T min = arr[0];

for (int i = 1; i < size; ++i) {

if (arr[i] < min) {

min = arr[i];

return min;

int main() {

int intArray[] = {5, 2, 8, 1, 9};

double doubleArray[] = {3.14, 2.71, 1.618};

int minInt = findMin(intArray, 5);

double minDouble = findMin(doubleArray, 3);

cout << "Minimum integer: " << minInt << endl;

cout << "Minimum double: " << minDouble << endl;

return 0;

}
OUTPUT:

Minimum integer: 1

Minimum double: 1.618

Explanation:

5. Template Declaration:
o template <typename T>: This declares the function template, indicating
that it can work with any data type T.
6. Function Definition:
o T findMin(const T arr[], int size):
▪ T: The return type of the function, which will be the same as the data
type of the array elements.
▪ const T arr[]: The array argument, where const ensures that the
array elements are not modified within the function.
▪ int size: The size of the array.
7. Initialization:
o T min = arr[0]: Initializes min to the first element of the array as a starting
point.
8. Finding the Minimum:
o The for loop iterates through the array from index 1 to size - 1.
o In each iteration, it compares arr[i] with min.
o If arr[i] is smaller than min, min is updated to arr[i].
9. Returning the Minimum:
o After the loop completes, min will contain the minimum value in the array.
o The function returns min.

Function Templates: A Primer

Function templates are a powerful feature in C++ that allow you to create generic functions
that can work with different data types. They provide a way to write reusable code without
having to create separate functions for each specific data type.

How Function Templates Work:

Template Instantiation:
o When you call the function template with specific arguments, the compiler
instantiates a specialized version of the function.
o For example, if you call findMin(intArray, 5), the compiler will
instantiate the function with T replaced by int.

Type Deduction:

o The compiler deduces the data type of the array elements based on the
argument provided (intArray).
o This allows you to use the function template without explicitly specifying the
data type.

Code Generation:

o The compiler generates the actual code for the specialized function,
replacing the template parameters with the specific data types.
o In this case, the compiler generates code that works specifically for arrays of
integers.

Benefits of Function Templates:

• Code Reusability: Function templates allow you to write generic code that can be
used with different data types.
• Flexibility: You can easily adapt function templates to different scenarios by
providing different template arguments.
• Type Safety: The compiler ensures type safety when using function templates,
preventing errors due to incorrect data types.
• Efficiency: The compiler can often optimize the generated code for specific data
types, resulting in better performance

unit-3

1.Write a C++ program for overloading a unary operator using friend function. CO2-AP

#include <iostream>

class Number {

private:

int value;
public:

Number(int v = 0){

value=v;

void display() {

cout << "Value: " << value << endl;

friend Number operator-(Number &n);

};

Number operator-(Number &n) {

Number temp;

temp.value = -n.value;

return temp;

int main() {

Number num(5);

cout << "Original ";

num.display();

Number result = -num;

cout << "After negation ";

result.display();

return 0;

Output:
Original Value: 5

After negation Value: -5

2. List the operators that cannot be overloaded. CO1-U

Operators that cannot be overloaded in C++:

• Scope resolution operator (::)


• Member selection operator (.)
• Member selection through pointer to function (->*)
• Ternary operator (?:)
• sizeof operator
• typeid operator
• Cast operators (static_cast, dynamic_cast, const_cast, reinterpret_cast)

3. Write a C++ program to illustrate Function overloading with different number of

arguments. CO2-AP

#include <iostream>

void print() {

cout << "No arguments" << endl;

void print(int a) {

cout << "One argument: " << a << endl;

void print(int a, int b) {

cout << "Two arguments: " << a << " and " << b << endl;

int main() {

print();

print(5);

print(10, 20);
return 0;

Output:

No arguments

One argument: 5

Two arguments: 10 and 20

4. Write a C++ program for overloading the unary minus operator. CO2-AP

#include <iostream>

class Number {

private:

int value;

public:

Number(int v = 0) {

value=v;

void display() {

cout << "Value: " << value << endl;

Number operator-() {

return Number(-value);

};
int main() {

Number num(5);

cout << "Original ";

num.display();

Number result = -num;

cout << "After negation ";

result.display();

return 0;

Output:

Original Value: 5

After negation Value: -5

5. Write a C++ program for illustrating function overloading using arguments of different
data

type. CO2-AP

#include <iostream>

#include <string>

void print(int i) {

cout << "Printing int: " << i << endl;

void print(double d) {

cout << "Printing double: " << d << endl;

void print(string s) {
cout << "Printing string: " << s << endl;

int main() {

print(5);

print(3.14);

print("Hello, World!");

return 0;

Output:

Printing int: 5

Printing double: 3.14

Printing string: Hello, World!

6. Define Abstract class with necessary example program. CO1-U

An abstract class in C++ is a class that cannot be instantiated and is designed to be a


base class for other classes. It contains at least one pure virtual function, which is
declared by assigning 0 to a virtual function in its declaration. This serves as a placeholder
for derived classes, which must provide an implementation for the pure virtual function

#include <iostream>

class Shape {

public:

virtual double area() = 0; // Pure virtual function

virtual void display() = 0; // Pure virtual function

};

class Circle : public Shape {

private:
double radius;

public:

Circle(double r) : radius(r) {}

double area() override {

return 3.14 * radius * radius;

void display() override {

cout << "Circle with radius " << radius << endl;

};

int main() {

// Shape shape; // This would cause an error - can't instantiate abstract class

Circle circle(5);

circle.display();

cout << "Area: " << circle.area() << endl;

return 0;

Output:

Circle with radius 5

Area: 78.5

7. Write a C++ program for swapping two integers, floating point values using function

Overloading.
#include <iostream>

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

int temp = a;

a = b;

b = temp;

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

float temp = a;

a = b;

b = temp;

int main() {

int x = 5, y = 10;

cout << "Before swap: x = " << x << ", y = " << y << endl;

swap(x, y);

cout << "After swap: x = " << x << ", y = " << y << endl;

float a = 2.5f, b = 7.9f;

cout << "Before swap: a = " << a << ", b = " << b << endl;

swap(a, b);

cout << "After swap: a = " << a << ", b = " << b << endl;

return 0;

}
Output:

Before swap: x = 5, y = 10

After swap: x = 10, y = 5

Before swap: a = 2.5, b = 7.9

After swap: a = 7.9, b = 2.5

8. What are the rules for operator overloading?

Rules for operator overloading:

• At least one operand must be a user-defined type.


• You cannot create new operators; only existing operators can be overloaded.
• The precedence and associativity of operators cannot be changed.
• Cannot change the number of operands an operator takes.
• Some operators cannot be overloaded (as mentioned in question 2).
• Overloaded operators cannot have default arguments.
• Operator overloading must be done either as a member function or as a friend
function.

unit-4

1.What is Hybrid Inheritance? Give example. CO1-U

Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of


inheritance. A common example is using both multiple inheritance and hierarchical
inheritance in the same program.

#include <iostream>

using namespace std;

class A {

protected:

int a;

public:

void set_a(int n) { a = n; }
};

class B : public A {

protected:

int b;

public:

void set_b(int n) { b = n; }

};

class C {

protected:

int c;

public:

void set_c(int n) { c = n; }

};

class D : public B, public C {

public:

void display() {

cout << "a = " << a << ", b = " << b << ", c = " << c << endl;

};

int main() {

D obj;

obj.set_a(10);
obj.set_b(20);

obj.set_c(30);

obj.display();

return 0;

Output:

a = 10, b = 20, c = 30

2 Develop a C++ program to calculate the total and average marks by getting Roll no and

marks from the user using Multiple inheritance. CO2-AP

#include <iostream>

#include <string>

using namespace std;

class Student {

protected:

int rollNo;

string name;

public:

void getStudentInfo() {

cout << "Enter Roll No: ";

cin >> rollNo;

cout << "Enter Name: ";

cin.ignore();

getline(cin, name);

}
};

class Marks {

protected:

int marks[3];

public:

void getMarks() {

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

cout << "Enter marks for subject " << i+1 << ": ";

cin >> marks[i];

};

class Result : public Student, public Marks {

public:

void calculateResult() {

int total = 0;

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

total += marks[i];

float average = total / 3.0;

cout << "\nStudent Details:" << endl;

cout << "Roll No: " << rollNo << endl;

cout << "Name: " << name << endl;


cout << "Total Marks: " << total << endl;

cout << "Average Marks: " << average << endl;

};

int main() {

Result student;

student.getStudentInfo();

student.getMarks();

student.calculateResult();

return 0;

Output:

Enter Roll No: 12

Enter Name: john

Enter marks for subject 1: 45

Enter marks for subject 2: 90

Enter marks for subject 3: 89

Student Details:

Roll No: 12

Name: john

Total Marks: 224

Average Marks: 74.6667

3 What is a virtual base class? Give example. CO1-U


Virtual Base Class: A virtual base class is used in virtual inheritance to prevent multiple
instances of a given class appearing in an inheritance hierarchy when using multiple
inheritance.
#include <iostream>

using namespace std;

class A {

public:

int a;

A() { a = 10; }

};

class B : virtual public A {

public:

int b;

B() { b = 20; }

};

class C : virtual public A {

public:

int c;

C() { c = 30; }

};

class D : public B, public C {

public:

int d;
D() { d = 40; }

};

int main() {

D obj;

cout << "a = " << obj.a << endl; // Only one copy of 'a' exists

cout << "b = " << obj.b << endl;

cout << "c = " << obj.c << endl;

cout << "d = " << obj.d << endl;

return 0;

Output

a = 10b = 20c = 30d = 40a = 10

b = 20

c = 30

d = 40

4. Write a C++ program to create a base class having the personal details of a
student .Createanother derived class that has the grade of the student. Use the concept of
single inheritanceand print all the details of the student.

#include <iostream>

#include <string>

using namespace std;

class PersonalDetails {

protected:
string name;

int age;

string address;

public:

void getPersonalDetails() {

cout << "Enter name: ";

getline(cin, name);

cout << "Enter age: ";

cin >> age;

cin.ignore();

cout << "Enter address: ";

getline(cin, address);

};

class Student : public PersonalDetails {

private:

string grade;

public:

void getGrade() {

cout << "Enter grade: ";

cin >> grade;

void displayDetails() {

cout << "\nStudent Details:" << endl;


cout << "Name: " << name << endl;

cout << "Age: " << age << endl;

cout << "Address: " << address << endl;

cout << "Grade: " << grade << endl;

};

int main() {

Student student;

student.getPersonalDetails();

student.getGrade();

student.displayDetails();

return 0;

Output:

Enter name: john

Enter age: 15

Enter address: aaa

Enter grade: o

Student Details:

Name: john

Age: 15

Address: aaa

Grade: o
5.Create a class ‘employee’ with all the relevant personal details. Inherit the properties of
this class in another class named ‘department’ which includes the designation and salary
details.Write a C++ program to print all the details of the employee.

#include <iostream>

#include <string>

using namespace std;

class Employee {

protected:

string name;

int age;

string address;

public:

void getEmployeeDetails() {

cout << "Enter name: ";

getline(cin, name);

cout << "Enter age: ";

cin >> age;

cin.ignore();

cout << "Enter address: ";

getline(cin, address);

};

class Department : public Employee {

private:
string designation;

double salary;

public:

void getDepartmentDetails() {

cout << "Enter designation: ";

getline(cin, designation);

cout << "Enter salary: ";

cin >> salary;

void displayDetails() {

cout << "\nEmployee Details:" << endl;

cout << "Name: " << name << endl;

cout << "Age: " << age << endl;

cout << "Address: " << address << endl;

cout << "Designation: " << designation << endl;

cout << "Salary: $" << salary << endl;

};

int main() {

Department emp;

emp.getEmployeeDetails();

emp.getDepartmentDetails();

emp.displayDetails();

return 0;
}

Output:

Enter name: john

Enter age: 45

Enter address: aa

Enter designation: sales

Enter salary: 70000

Employee Details:

Name: john

Age: 45

Address: aa

Designation: sales

Salary: $70000

6 Differentiate runtime and compile time polymorphism. CO1-U

Compile-time polymorphism (static binding):


• Achieved through function overloading and operator overloading
• Resolved at compile time
• Example: Method overloading
Runtime polymorphism (dynamic binding):
• Achieved through function overriding using virtual functions
• Resolved at runtime
• Example: Method overriding in inheritance

7 Develop a C++ program to get a number from a user using virtual base class.

#include <iostream>

using namespace std;


class Input {

public:

virtual void getInput() = 0;

};

class NumberInput : virtual public Input {

protected:

int number;

public:

void getInput() override {

cout << "Enter a number: ";

cin >> number;

};

class Display : virtual public Input {

public:

virtual void showInput() = 0;

};

class NumberDisplay : public NumberInput, public Display {

public:

void showInput() override {

cout << "The number you entered is: " << number << endl;

};
int main() {

NumberDisplay nd;

nd.getInput();

nd.showInput();

return 0;

Output

Enter a number: 5

The number you entered is: 5

8 What is a pure virtual function? Give example. CO1-U

Pure Virtual Function: A pure virtual function is a virtual function that has no definition in
the base class and must be implemented by any concrete (non-abstract) derived class. It's
declared by assigning 0 to the function declaration.

#include <iostream>

using namespace std;

class Shape {

public:

virtual double area() = 0; // Pure virtual function

};

class Circle : public Shape {

private:

double radius;

public:
Circle(double r) : radius(r) {}

double area() override {

return 3.14 * radius * radius;

};

class Rectangle : public Shape {

private:

double length, width;

public:

Rectangle(double l, double w) : length(l), width(w) {}

double area() override {

return length * width;

};

int main() {

Circle c(5);

Rectangle r(4, 6);

cout << "Area of circle: " << c.area() << endl;

cout << "Area of rectangle: " << r.area() << endl;

return 0;

Output:
Area of circle: 78.5

Area of rectangle: 24

UNIT - V

1 What is a function template? Give example. CO1-U

Function Template: A function template is a generic function that can work with different
data types. It allows you to write a function once and use it with various data types without
rewriting the code for each type.

#include <iostream>

using namespace std;

template <typename T>

T add(T a, T b) {

return a + b;

int main() {

cout << "Sum of integers: " << add(5, 3) << endl;

cout << "Sum of doubles: " << add(3.14, 2.5) << endl;

return 0;

output:

Sum of integers: 8

Sum of doubles: 5.64

2 Will exception handling improve the efficiency of programming? Justify your answer.
CO1-U
• Separation of error-handling code from normal code, improving readability and
maintainability.
• Grouping of error types and centralized handling, making it easier to manage
different error scenarios.
• Propagation of errors up the call stack, allowing errors to be handled at the
appropriate level.
• Preventing program crashes by catching and handling unexpected situations
gracefully.

3 Write a function template for finding the minimum value contained in an array CO2-AP

#include <iostream>

using namespace std;

template <typename T>

T findMin(T arr[], int size) {

if (size == 0) {

throw runtime_error("Array is empty");

T min = arr[0];

for (int i = 1; i < size; i++) {

if (arr[i] < min) {

min = arr[i];

return min;

int main() {
int intArr[] = {5, 2, 8, 1, 9};

double doubleArr[] = {3.14, 2.71, 1.41, 2.0};

cout << "Minimum in int array: " << findMin(intArr, 5) << endl;

cout << "Minimum in double array: " << findMin(doubleArr, 4) << endl;

return 0;

Output:

Minimum in int array: 1

Minimum in double array: 1.41

4 Write a C++ program to handle a single try, catch exceptions for your own problem

situation. CO2-AP

#include <iostream>

#include <stdexcept>

using namespace std;

double divide(double a, double b) {

if (b == 0) {

throw runtime_error("Division by zero!");

return a / b;

int main() {

double numerator, denominator;


cout << "Enter numerator: ";

cin >> numerator;

cout << "Enter denominator: ";

cin >> denominator;

try {

double result = divide(numerator, denominator);

cout << "Result: " << result << endl;

} catch (const runtime_error& e) {

cout << "Error: " << e.what() << endl;

return 0;

Output

Enter numerator: 9

Enter denominator: 0ERROR!

Error: Division by zero!

5 Develop a C++ program to design a simple calculator using class template CO2-AP

#include <iostream>

using namespace std;

template <typename T>

class Calculator {
private:

T num1, num2;

public:

Calculator(T a, T b) : num1(a), num2(b) {}

T add() { return num1 + num2; }

T subtract() { return num1 - num2; }

T multiply() { return num1 * num2; }

T divide() {

if (num2 == 0) {

throw runtime_error("Division by zero!");

return num1 / num2;

};

int main() {

try {

Calculator<int> intCalc(10, 5);

cout << "Integer calculations:" << endl;

cout << "Addition: " << intCalc.add() << endl;

cout << "Subtraction: " << intCalc.subtract() << endl;

cout << "Multiplication: " << intCalc.multiply() << endl;

cout << "Division: " << intCalc.divide() << endl;


Calculator<double> doubleCalc(7.5, 2.5);

cout << "\nDouble calculations:" << endl;

cout << "Addition: " << doubleCalc.add() << endl;

cout << "Subtraction: " << doubleCalc.subtract() << endl;

cout << "Multiplication: " << doubleCalc.multiply() << endl;

cout << "Division: " << doubleCalc.divide() << endl;

} catch (const runtime_error& e) {

cout << "Error: " << e.what() << endl;

return 0;

Output:

Integer calculations:

Addition: 15

Subtraction: 5

Multiplication: 50

Division: 2

Double calculations:

Addition: 10

Subtraction: 5

Multiplication: 18.75

Division: 3

6 Develop a C++ program to add 2 numbers using function template CO2-AP

#include <iostream>
using namespace std;

template <typename T>

T addNumbers(T a, T b) {

return a + b;

int main() {

int int1 = 5, int2 = 10;

double double1 = 3.14, double2 = 2.5;

cout << "Sum of integers: " << addNumbers(int1, int2) << endl;

cout << "Sum of doubles: " << addNumbers(double1, double2) << endl;

return 0;

Output

Sum of integers: 15

Sum of doubles: 5.64

7 Write down the syntax for Multiple catch statement. Give an example. CO1-U

try {

// Code that may throw exceptions

} catch (ExceptionType1 e1) {

// Handle exception of ExceptionType1

} catch (ExceptionType2 e2) {

// Handle exception of ExceptionType2


} catch (...) {

// Handle any other exception

Eg:

#include <iostream>

#include <stdexcept>

using namespace std;

void checkValue(int value) {

if (value < 0) {

throw runtime_error("Negative value");

} else if (value == 0) {

throw logic_error("Zero value");

} else if (value > 100) {

throw out_of_range("Value too large");

cout << "Value is: " << value << endl;

int main() {

try {

checkValue(-5);

} catch (const runtime_error& e) {

cout << "Runtime error: " << e.what() << endl;

} catch (const logic_error& e) {

cout << "Logic error: " << e.what() << endl;


} catch (const out_of_range& e) {

cout << "Out of range error: " << e.what() << endl;

} catch (...) {

cout << "Unknown exception occurred" << endl;

return 0;

Output:

ERROR!

Runtime error: Negative value

8 Develop a C++ program for illustrating array index out of bound exception.

#include <iostream>

#include <stdexcept>

using namespace std;

int main() {

int arr[5] = {1, 2, 3, 4, 5};

int index;

cout << "Enter an index to access the array: ";

cin >> index;

try {

if (index < 0 || index >= 5) {


throw out_of_range("Array index out of bounds");

cout << "Value at index " << index << " is: " << arr[index] << endl;

} catch (const out_of_range& e) {

cout << "Error: " << e.what() << endl;

cout << "Valid indices are 0 to 4" << endl;

return 0;

Output:

Enter an index to access the array: 8

ERROR!

Error: Array index out of bounds

Valid indices are 0 to 4

Part B

Unit 3

1.Write a C++ program to swap two integers, floats, characters and two strings

using function overloading concept. CO2- AP (16)

PROGRAM:
#include <iostream>
#include <string>
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
void swap(float &x, float &y) {
float temp = x;
x = y;
y = temp;
}

void swap(char &x, char &y) {


char temp = x;
x = y;
y = temp;
}

void swap(string &x, string &y) {


string temp = x;
x = y;
y = temp;
}
int main() {
int a = 10, b = 20;
float c = 3.14, d = 2.718;
char e = 'A', f = 'B';
string g = "Hello", h = "World";
swap(a, b);
swap(c, d);
swap(e, f);
swap(g, h);
cout << "Swapped integers: " << a << " and " << b << endl;
cout << "Swapped floats: " << c << " and " << d << endl;
cout << "Swapped characters: " << e << " and " << f << endl;
cout << "Swapped strings: " << g << " and " << h << endl;
return 0;
}
OUTPUT:
Swapped integers: 20 and 10
Swapped floats: 2.718 and 3.14
Swapped characters: B and A
Swapped strings: World and Hello

2 Write a C++ program to perform complex number addition, subtraction,

multiplication using operator overloading with friend functions. CO2- AP (16)

#include <iostream>

class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) {
real=r;
imag=i;
}

void display() {
cout << real;
if (imag >= 0) {
cout << " + " << imag << "i";
}
else{
cout << " - " << -imag << "i";
}
}
friend Complex operator + ( Complex c1, Complex c2);
friend Complex operator - ( Complex c1, Complex c2);
friend Complex operator * ( Complex c1, Complex c2);
};

Complex operator + (Complex c1, Complex c2) {


return Complex(c1.real + c2.real, c1.imag + c2.imag);
}

Complex operator - ( Complex c1, Complex c2) {


return Complex(c1.real - c2.real, c1.imag - c2.imag);
}

Complex operator * ( Complex c1, Complex c2) {


return Complex(
c1.real * c2.real - c1.imag * c2.imag,
c1.real * c2.imag + c1.imag * c2.real
);
}
int main() {
Complex c1(3.0, 2.0);
Complex c2(1.0, 7.0);
Complex result;

result = c1 + c2;
cout << "Sum: ";
result.display();

result = c1 - c2;
cout << "Difference: ";
result.display();

result = c1 * c2;
cout << "Product: ";
result.display();

return 0;
}

SAMPLE OUTPUT:

Sum: 4 + 9i
Difference: 2 - 5i
Product: -11 + 23i

3 Write a C++ program to perform complex number addition, subtraction,

multiplication using operator overloading with member functions. CO2- AP (16)

#include <iostream>
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) {
real=r;
imag=i;
}
void display() {
cout << real;
if (imag >= 0){
cout << " + " << imag << "i";
}
else{
cout << " - " << -imag << "i";
}
}

Complex operator + ( Complex other) {


return Complex(real + other.real, imag + other.imag);
}
Complex operator - (Complex other) {
return Complex(real - other.real, imag - other.imag);
}
Complex operator * ( Complex other) {
return Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
);
}
};

int main() {
Complex c1(3.0, 2.0);
Complex c2(1.0, 7.0);
Complex result;
result = c1 + c2;
cout << "Sum: ";
result.display();
result = c1 - c2;
cout << "Difference: ";
result.display();
result = c1 * c2;
cout << "Product: ";
result.display()
return 0;
}
SAMPLE OUTPUT:
Sum: 4 + 9i
Difference: 2 - 5i
Product: -11 + 23i

(4)(i)Write a C++ program to find the volume of cube, cone and rectangle using

function overloading.

#include <iostream>
#include <cmath>
const double PI = 3.14;
double calculateVolume(double side) {
return side * side * side;
}

double calculateVolume(double radius, double height){


return (1.0/3.0) * PI * radius * radius * height;
}
double calculateVolume(double length, double width, double height) {
return length * width * height;
}
int main() {
double cubeSide = 5.0;
cout << "Volume of cube with side " << cubeSide
<< " is: " << calculateVolume(cubeSide) <<endl;
double coneRadius = 3.0, coneHeight = 4.0;
cout << "Volume of cone with radius " << coneRadius
<< " and height " << coneHeight
<< " is: " << calculateVolume(coneRadius, coneHeight) <<endl;
double boxLength = 2.0, boxWidth = 3.0, boxHeight = 4.0;
cout << "Volume of rectangular box with length " << boxLength << ", width "
<< boxWidth<< ", and height " << boxHeight<< " is: " <<
calculateVolume(boxLength, boxWidth, boxHeight) <<endl;
return 0;
}
OUTPUT: Volume of cube with side 5 is: 125
Volume of cone with radius 3 and height 4 is: 37.68
Volume of rectangular box with length 2, width 3, and height 4 is: 24
RESULT:

Ii)Write a C++ program to find the sum of two integers, two floating point values

and three integers using function overloading.

#include <iostream>

using namespace std;

// Function to sum two integers

int sum(int a, int b) {

return a + b;

// Function to sum two floating-point values


double sum(double a, double b) {

return a + b;

// Function to sum three integers

int sum(int a, int b, int c) {

return a + b + c;

int main() {

// Test sum of two integers

int int1 = 5, int2 = 10;

cout << "Sum of two integers (" << int1 << ", " << int2 << "): "

<< sum(int1, int2) << endl;

// Test sum of two floating-point values

double double1 = 3.14, double2 = 2.5;

cout << "Sum of two floating-point values (" << double1 << ", " << double2 << "): "

<< sum(double1, double2) << endl;

// Test sum of three integers

int int3 = 15;

cout << "Sum of three integers (" << int1 << ", " << int2 << ", " << int3 << "): "

<< sum(int1, int2, int3) << endl;

return 0;
}

Output

Sum of two integers (5, 10): 15

Sum of two floating-point values (3.14, 2.5): 5.64

Sum of three integers (5, 10, 15): 30

5 Write a C++ program to perform matrix addition, subtraction, multiplication

using operator overloading with member functions. CO2- AP (16)

#include <iostream>

class Matrix {
private:
int data[2][2]; // Simplified to 2x2 matrices

public:
void input() {
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
cin >> data[i][j];
}

void display() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
cout << data[i][j] << " ";
cout << endl;
}
}

Matrix operator+(Matrix other) {


Matrix result;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
result.data[i][j] = data[i][j] + other.data[i][j];
return result;
}

Matrix operator-(Matrix other) {


Matrix result;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
result.data[i][j] = data[i][j] - other.data[i][j];
return result;
}

Matrix operator*(Matrix other) {


Matrix result;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
result.data[i][j] = data[i][0] * other.data[0][j] +
data[i][1] * other.data[1][j];
return result;
}
};

int main() {
Matrix m1, m2;

cout << "Enter elements for the first 2x2 matrix:" << endl;
m1.input();

cout << "Enter elements for the second 2x2 matrix:" << endl;
m2.input();

cout << "Matrix 1:" << endl;


m1.display();
cout << "Matrix 2:" << endl;
m2.display();
cout << "Addition Result:" << endl;
(m1 + m2).display()
cout << "Subtraction Result:" << endl;
(m1 - m2).display();
cout << "Multiplication Result:" << endl;
(m1 * m2).display();
return 0;
}

SAMPLE INPUT:
Enter elements for the first 2x2 matrix:
2
3
6
7
Enter elements for the second 2x2 matrix:
8
9
3
1
SAMPLE OUTPUT:
Matrix 1:
23
67
Matrix 2:
89
31
Addition Result:
10 12
98
Subtraction Result:
-6 -6
36
Multiplication Result:
25 21
69 61

6 Write a C++ program to overload any two binary arithmetic operators with

member functions. CO2- AP (16)

#include <iostream>

using namespace std;

class Complex {

private:

float real;

float imag;

public:

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

// Overload the + operator

Complex operator+(const Complex &other) {

return Complex(real + other.real, imag + other.imag);

// Overload the - operator

Complex operator-(const Complex &other) {

return Complex(real - other.real, imag - other.imag);


}

void display() {

cout << real << " + " << imag << "i" << endl;

};

int main() {

Complex c1(3.5, 2.5), c2(1.5, 4.5);

Complex sum = c1 + c2; // Using overloaded + operator

Complex diff = c1 - c2; // Using overloaded - operator

cout << "Sum: ";

sum.display();

cout << "Difference: ";

diff.display();

return 0;

output

Sum: 5 + 7i

Difference: 2 + -2i

7 What is operator overloading? Explain unary operator overloading with

example. CO1- U (16)

C++ provides a special function to change the current functionality of some


operators within its class which is often called as operator overloading.
Operator Overloading is the method by which we can change some specific
operators’ functions to do different tasks.

Syntax:
Return_Type classname :: operator op(Argument list)
{
Function Body
} // This can be done by declaring the function

Here,

• Return_Type is the value type to be returned to another object.


• operator op is the function where the operator is a keyword.
• op is the operator to be overloaded.
Operator Overloading can be done by using two approaches, i.e.

1. Overloading Unary Operator.


2. Overloading Binary Operator.
Criteria/Rules to Define the Operator Function
3. In the case of a non-static member function, the binary operator should
have only one argument and the unary should not have an argument.
4. In the case of a friend function, the binary operator should have only two
arguments and the unary should have only one argument.
5. Operators that cannot be overloaded are .* :: ?:
6. Operators that cannot be overloaded when declaring that function as
friend function are = () [] ->.
7. The operator function must be either a non-static (member function),
global free function or a friend function.

Unary Operator Overloading with Example

Unary operators (like ++, --, !, etc.) can be overloaded to work with objects of a class.

Syntax:
class className {
...
public:
returnType operator<symbol>()
{
// custom behaviour for the operator
}
...
};

Example: Overloading Unary Minus (-) Operator

#include <iostream>

class Number {

private:

int value;

public:

Number(int v = 0) {

value=v;

void display() {

cout << "Value: " << value << endl;

Number operator-() {

return Number(-value);

};
int main() {

Number num(5);

cout << "Original ";

num.display();

Number result = -num;

cout << "After negation ";

result.display();

return 0;

Output:

Original Value: 5

After negation Value: -5

8 How will you overload binary operators using friend functions? Explain with

examples CO1- U (16)

9.

What is function overloading? Explain the types of function overloading with

respect to the number of arguments and data type of arguments using example

Programs.

10 Explain in detail about unary and binary operator overloading with suitable

Examples.
Operator overloading in C++ allows you to define how operators work with user-defined
types (like classes). Operators can be classified into unary and binary operators based on
the number of operands they require.

Unary Operator Overloading

Unary operators operate on a single operand. Common unary operators include ++, --, -,
+, and logical NOT (!). To overload a unary operator, you can define a member function or a
friend function.

Example: Overloading Unary Operators

Let's create a class called Complex to represent complex numbers and overload the unary
- (negation) operator and the unary ++ (increment) operator.

#include <iostream>

class Complex {
private:
double real; // Real part
double imag; // Imaginary part

public:
// Constructor
Complex(double r = 0, double i = 0) : real(r), imag(i) {}

// Overloading the unary - operator (negation)


Complex operator-() {
return Complex(-real, -imag);
}

// Overloading the unary ++ operator (prefix increment)


Complex operator++() {
++real; // Increment real part
++imag; // Increment imaginary part
return *this; // Return current object
}

// Function to display the complex number


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

int main() {
Complex c1(3.0, 4.0);

std::cout << "Original: ";


c1.display(); // 3.0 + 4.0i

Complex c2 = -c1; // Using overloaded unary - operator


std::cout << "Negation: ";
c2.display(); // -3.0 - 4.0i

++c1; // Using overloaded unary ++ operator


std::cout << "After Increment: ";
c1.display(); // 4.0 + 5.0i

return 0;
}

Output

go
Copy code
Original: 3 + 4i
Negation: -3 + -4i
After Increment: 4 + 5i

Binary Operator Overloading

Binary operators operate on two operands. Common binary operators include +, -, *, /,


and ==. You can overload binary operators by defining a member function or a friend
function.
Example: Overloading Binary Operators

We will extend the Complex class to overload the binary + (addition) and - (subtraction)
operators.

#include <iostream>

class Complex {
private:
double real; // Real part
double imag; // Imaginary part

public:
// Constructor
Complex(double r = 0, double i = 0) : real(r), imag(i) {}

// Overloading the + operator (addition)


Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}

// Overloading the - operator (subtraction)


Complex operator-(const Complex& other) {
return Complex(real - other.real, imag - other.imag);
}

// Function to display the complex number


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

int main() {
Complex c1(3.0, 4.0);
Complex c2(1.5, 2.5);

Complex c3 = c1 + c2; // Using overloaded + operator


cout << "Addition: ";
c3.display(); // 4.5 + 6.5i
Complex c4 = c1 - c2; // Using overloaded - operator
cout << "Subtraction: ";
c4.display(); // 1.5 + 1.5i

return 0;
}
Addition: 4.5 + 6.5i
Subtraction: 1.5 + 1.5i

Summary

• Unary Operator Overloading: Involves overloading operators that work with a


single operand. We demonstrated this with the unary - operator (negation) and the
unary ++ operator (increment).
• Binary Operator Overloading: Involves overloading operators that work with two
operands. We demonstrated this with the binary + (addition) and - (subtraction)
operators.

Operator overloading enhances the readability and usability of your code, allowing you to
use standard operators with user-defined types seamlessly.

Unit-4

Imagine a publishing company that markets both book and audio-cassette

versions of its work. Create a class publication that stores the title and price.

From this class derive two classes book and tape; book includes one more

property: page numbers and tape contains its length in minutes (float). Each of

these classes must have getdata( ) functions and putdata ( ) functions to

input/output its data. Write a main function to test the book and tape classes.

ALGORITHM:

• Declare title and price as public member variables.


• Implement getdata() and putdata() virtual functions for input and output.
• Inherit from Publication.
• Declare pages as a public member variable.
• Override getdata() to input pages.
• Override putdata() to display pages.
• Inherit from Publication.
• Declare length as a public member variable.
• Override getdata() to input length.
• Override putdata() to display length.
• Declare objects of Book and Tape classes.
• Call getdata() on the Book object to input title, price, and pages.
• Call getdata() on the Tape object to input title, price, and length.
• Call putdata() on the Book object to display title, price, and pages.
• Call putdata() on the Tape object to display title, price, and length.
• Return 0 from the main function.
• Use a C++ compiler to compile the code.
• Execute the compiled program to see the output.

PROGRAM:

#include <iostream>
#include <string>

class Publication {
public:
string title;
double price;

virtual void getdata() {


cout << "Enter title: ";
Cin>>title;
cout << "Enter price: ";
cin >> price;
}

virtual void putdata() {


cout << "Title: " << title << endl;
cout << "Price: " << price << endl;
}
};

class Book : public Publication {


public:
int pages;

void getdata(){
Publication::getdata();
cout << "Enter number of pages: ";
cin >> pages;
}

void putdata() {
Publication::putdata();
cout << "Pages: " << pages << endl;
}
};

class Tape : public Publication {


public:
float length;

void getdata() {
Publication::getdata();
cout << "Enter length in minutes: ";
cin >> length;
}
void putdata() {
Publication::putdata();
cout << "Length: " << length << endl;
}
};

int main() {
Book book;
Tape tape;

cout << "Enter book details:\n";


book.getdata();

cout << "Enter tape details:\n";


tape.getdata();

cout << "\nBook details:\n";


book.putdata();

cout << "\nTape details:\n";


tape.putdata();

return 0;
}

SAMPLE INPUT:

Enter book details:


Enter title: sunshine
Enter price: 150
Enter number of pages: 89
Enter tape details:
Enter title: sunshine
Enter price: 150
Enter length in minutes: 67.9

SAMPLE OUTPUT:

Book details:
Title: sunshine
Price: 150
Pages: 89

Tape details:
Title: sunshine
Price: 150
Length: 67.9

2 Create three classes Student, Test and Result classes. The student class

contains student relevant information. Test class contains marks for five

subjects. The result class contains Total and average of the marks obtained in

five subjects. Inherit the properties of Student and Test class details in Result

class through multilevel inheritance.

ALGORITHM:

• Declare name and roll_number as public member variables.


• Implement getStudentDetails() and displayStudentDetails() functions for
input and output.
• Inherit from Student.
• Declare marks as an array to store marks for 5 subjects.
• Implement getTestMarks() and displayTestMarks() functions for input and
output.
• Inherit from Test.
• Declare total_marks and average_marks as public member variables.
• Implement calculateResult() to calculate total and average marks.
• Implement displayResult() to display total and average marks.
• Declare an object of the Result class.
• Call getStudentDetails() on the Result object to input name and roll number.
• Call getTestMarks() on the Result object to input marks for 5 subjects.
• Call calculateResult() on the Result object to calculate total and average
marks.
• call displayStudentDetails(), displayTestMarks(), and displayResult() on the
Result object to display all the information.

PROGRAM:

#include <iostream>
#include <string>

class Student {
public:
string name;
int roll_number;

void getStudentDetails() {
cout << "Enter student name: ";
getline(cin, name);
cout << "Enter student roll number: ";
cin >> roll_number;
}

void displayStudentDetails() {
cout << "Student Name: " << name << endl;
cout << "Student Roll Number: " << roll_number << endl;
}
};
class Test : public Student {
public:
int marks[5];

void getTestMarks() {
cout << "Enter marks for 5 subjects:\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << i + 1 << ": ";
cin >> marks[i];
}
}

void displayTestMarks() {
cout << "Test Marks:\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << i + 1 << ": " << marks[i] << endl;
}
}
};

class Result : public Test {


public:
int total_marks;
float average_marks;

void calculateResult() {
total_marks = 0;
for (int i = 0; i < 5; i++) {
total_marks += marks[i];
}
average_marks = total_marks / 5.0;
}

void displayResult() {
cout << "Total Marks: " << total_marks << endl;
cout << "Average Marks: " << average_marks << endl;
}
};

int main() {
Result result;

result.getStudentDetails();
result.getTestMarks();
result.calculateResult();

result.displayStudentDetails();
result.displayTestMarks();
result.displayResult();

return 0;
}
SAMPLE INPUUT:

Enter student name: Abi


Enter student roll number: 3
Enter marks for 5 subjects:
Subject 1: 99
Subject 2: 98
Subject 3: 100
Subject 4: 97
Subject 5: 99

SAMPLE OUTPUT:

Student Name: Abi


Student Roll Number: 3
Test Marks:
Subject 1: 99
Subject 2: 98
Subject 3: 100
Subject 4: 97
Subject 5: 99
Total Marks: 493
Average Marks: 98.6

3 Create three classes Student, Test and Result classes. The student class

contains student relevant information. Test class contains marks for five

subjects. The result class contains Total and average of the marks obtained

five subjects. Inherit the properties of Student and Test class details in Result

class through multiple inheritance.

ALGORITHM:
• Declare name and roll_number as public member variables.
• Implement getStudentDetails() and displayStudentDetails() functions for
input and output.
• Declare marks as an array to store marks for 5 subjects.
• Implement getTestMarks() and displayTestMarks() functions for input and
output.
• Inherit from both Student and Test using multiple inheritance.
• Declare total_marks and average_marks as public member variables.
• Implement calculateResult() to calculate total and average marks.
• Implement displayResult() to display total and average marks.
• Declare an object of the Result class.
• Call getStudentDetails() on the Result object to input name and roll number.
• Call getTestMarks() on the Result object to input marks for 5 subjects.
• Call calculateResult() on the Result object to calculate total and average
marks.
• Call displayStudentDetails(), displayTestMarks(), and displayResult() on the
Result object to display all the information.

PROGRAM:
#include <iostream>
#include <string>

class Student {
public:
string name;
int roll_number;

void getStudentDetails() {
cout << "Enter student name: ";
cin>>name;
cout << "Enter student roll number: ";
cin >> roll_number;
}
void displayStudentDetails() {
cout << "Student Name: " << name << endl;
cout << "Student Roll Number: " << roll_number << endl;
}
};

class Test {
public:
int marks[5];
void getTestMarks() {
cout << "Enter marks for 5 subjects:\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << i + 1 << ": ";
cin >> marks[i];
}
}
void displayTestMarks() {
cout << "Test Marks:\n";
for (int i = 0; i < 5; i++) {
cout << "Subject " << i + 1 << ": " << marks[i] << endl;
}
}
};

class Result : public Student, public Test {


public:
int total_marks;
float average_marks;
void calculateResult() {
total_marks = 0;
for (int i = 0; i < 5; i++) {
total_marks += marks[i];
}
average_marks = total_marks / 5.0;
}

void displayResult() {
cout << "Total Marks: " << total_marks << endl;
cout << "Average Marks: " << average_marks << endl;
}
};

int main() {
Result result;

result.getStudentDetails();
result.getTestMarks();
result.calculateResult();
result.displayStudentDetails();
result.displayTestMarks();
result.displayResult();

return 0;
}

SAMPLE INPUT:

Enter student name: Abi


Enter student roll number: 03
Enter marks for 5 subjects:
Subject 1: 98
Subject 2: 98
Subject 3: 98
Subject 4: 98
Subject 5: 98

SAMPLE OUTPUT:

Student Name: Abi


Student Roll Number: 3
Test Marks:
Subject 1: 98
Subject 2: 98
Subject 3: 98
Subject 4: 98
Subject 5: 98
Total Marks: 490
Average Marks: 98

4
Create a base class Shape with relevant data members and member functions to

get data and print the area. Create two more classes Rectangle and Triangle

which inherit Shape class. Make the print data function as virtual function in

base class. Write a C++ main ( ) function to check this.

CO2- AP (16)

Write a C++ program to calculate the area of a circle and triangle using pure

virtual functions. Write the rules for virtual functions and a C++ program for

implementing virtual funtions

C++ Program Using Pure Virtual Functions

cpp
Copy code
#include <iostream>
#include <cmath>

using namespace std;

// Abstract base class


class Shape {
public:
// Pure virtual function
virtual double area() = 0; // No definition
};

// Derived class for Circle


class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}

// Implementation of area() for Circle


double area() override {
return M_PI * radius * radius; // Area of circle: πr²
}
};

// Derived class for Triangle


class Triangle : public Shape {
private:
double base;
double height;

public:
Triangle(double b, double h) : base(b), height(h) {}

// Implementation of area() for Triangle


double area() override {
return 0.5 * base * height; // Area of triangle: 1/2 * base *
height
}
};

int main() {
// Create objects for Circle and Triangle
Shape* circle = new Circle(5.0);
Shape* triangle = new Triangle(4.0, 3.0);

// Calculate and display areas


cout << "Area of Circle: " << circle->area() << endl; // Calls
Circle's area()
cout << "Area of Triangle: " << triangle->area() << endl; // Calls
Triangle's area()

// Clean up
delete circle;
delete triangle;

return 0;
}

Explanation

8. Abstract Base Class: Shape is an abstract class because it contains a pure virtual
function area(). This means you cannot create an instance of Shape directly.
9. Derived Classes:
o Circle: Implements the area() function using the formula for the area of a
circle.
o Triangle: Implements the area() function using the formula for the area of
a triangle.
10. Polymorphism: In main(), we use pointers of type Shape to refer to the objects of
derived classes. This demonstrates polymorphism: the correct area() function is
called based on the object type.
11. Memory Management: We use new to allocate memory for the objects and delete
to free that memory.

Rules for Virtual Functions

12. Declared in Base Class: A virtual function is declared in a base class using the
keyword virtual.
13. Can be Overridden: A derived class can override a virtual function to provide
specific implementation.
14. Pure Virtual Function: Declared by assigning = 0 in the base class, making it
abstract (cannot be instantiated).
15. Dynamic Binding: The appropriate function is determined at runtime based on the
object type, not the pointer type.
16. Destructors: If a class has virtual functions, it should have a virtual destructor to
ensure proper cleanup of derived class objects when deleted through base class
pointers.

Create three classes Employee, Boss and CEO. Employee class stores basic
details like, name, employee no, department. The Boss class gets the salary

and calculates the bonus as 10% of the salary. The CEO class contains shares

details that the employee owns. An employee is allowed to own a share only if

the salary exceeds 50,000. Include Info ( ) and writeInfo( ) functions in all the

classes. Use the inheritance concept and display the employee details with

bonus and shares eligibility.

ALGORITHM:
• Declare name, employee_no, department, and salary as protected member
variables.
• Implement AskInfo() and WriteInfo() functions for input and output.
• Inherit from Employee.
• Declare bonus as a private member variable.
• Implement AskInfo() to call the base class function first and then ask for
bonus.
• Implement WriteInfo() to call the base class function first and then display
bonus.
• Inherit from Boss.
• Declare shares as a private member variable.
• Implement AskInfo() to call the base class function first and then ask for
shares.
• Implement WriteInfo() to call the base class function first and then display
shares.
• Declare an object of the CEO class.
• Call AskInfo() on the CEO object to input information.
• Call WriteInfo() on the CEO object to display the entered information.

PROGRAM:
#include <iostream>
#include <string>
class Employee {
protected:
string name;
int employee_no;
string department;
double salary;

public:
void AskInfo() {
cout << "Enter employee name: ";
cin>>name;
cout << "Enter employee number: ";
cin >> employee_no;
cout << "Enter department: ";
cin>>department;
cout << "Enter salary: ";
cin >> salary;
}

void WriteInfo() {
cout << "\nEmployee Name: " << name << endl;
cout << "Employee Number: " << employee_no << endl;
cout << "Department: " << department << endl;
cout << "Salary: " << salary << endl;
}
};

class Boss : public Employee {


private:
double bonus;
public:
void AskInfo() {
Employee::AskInfo();
cout << "Enter bonus: ";
cin >> bonus;
}

void WriteInfo() {
Employee::WriteInfo();
cout << "Bonus: " << bonus << endl;
}
};

class CEO : public Boss {


private:
int shares;

public:
void AskInfo() {
Boss::AskInfo();
cout << "Enter number of shares owned: ";
cin >> shares;
}
void WriteInfo() {
Boss::WriteInfo();
cout << "Shares Owned: " << shares << endl;
}
};

int main() {
CEO ceo;
cout << "Enter CEO information:\n";
ceo.AskInfo();
cout << "\nCEO Information:\n";
ceo.WriteInfo();
return 0;
}
SAMPLE INPUT:

Enter CEO information:


Enter employee name: john
Enter employee number: 23
Enter department: manufacturing
Enter salary: 50000
Enter bonus: 5000
Enter number of shares owned: 2

SAMPLE OUTPUT:

CEO Information:
Employee Name: john
Employee Number: 23
Department: manufacturing
Salary: 50000
Bonus: 5000

Unit 5

Write a C++ program to divide two integers and floating point values.

The code should throw an exception when the divisor is zero.

#include <iostream>

#include <stdexcept> // For std::runtime_error

using namespace std;

// Function to divide two integers

double divide(int numerator, int denominator) {

if (denominator == 0) {
throw runtime_error("Division by zero is not allowed.");

return static_cast<double>(numerator) / denominator;

// Function to divide two floating-point values

double divide(double numerator, double denominator) {

if (denominator == 0.0) {

throw runtime_error("Division by zero is not allowed.");

return numerator / denominator;

int main() {

try {

int intNumerator = 10, intDenominator = 0;

cout << "Integer Division: " << divide(intNumerator, intDenominator) << endl;

double floatNumerator = 10.0, floatDenominator = 2.0;

cout << "Floating Point Division: " << divide(floatNumerator, floatDenominator) << endl;

} catch (const runtime_error& e) {

cout << "Error: " << e.what() << endl; // Handle the division by zero error

return 0;
}

Output:

Error: Division by zero is not allowed.

Write a C++ program to demonstrate the concept of re-throwing an

exception.

#include <iostream>

#include <stdexcept> // For std::runtime_error

using namespace std;

void processDivision(int numerator, int denominator) {

try {

if (denominator == 0) {

throw runtime_error("Division by zero is not allowed.");

cout << "Result: " << static_cast<double>(numerator) / denominator << endl;

} catch (const runtime_error& e) {

// Re-throw the exception to be handled further up the call stack

throw;

int main() {

try {

processDivision(10, 0);
} catch (const runtime_error& e) {

cout << "Caught in main: " << e.what() << endl; // Handle the re-thrown exception

return 0;

Output:

Caught in main: Division by zero is not allowed.

You might also like