Oops Answer
Oops Answer
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:
#include <iostream>
class ShapeCalculator {
public:
cout << "Area of square with side " << side << " is: " << area << endl;
<< " and width " << width << " is: " << area << endl;
};
int main() {
ShapeCalculator calculator;
calculator.printArea(5.0);
calculator.printArea(4.0, 6.0);
return 0;
Output:
Explanation:
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>
void greet() {
cout << "Hello, " << name << "!" << endl;
int main() {
Output:
Hello!
Hello, Alice!
Explanation:
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>
return a + b;
}
return a + b;
int main() {
return 0;
Output:
Result 1: 8
Result 2: 6.2
Explanation:
14b) How will you overload binary operators using friend functions? Explain with
examples.
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,
#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);
int main() {
Complex c1(3, 2);
Complex c2(1, 4);
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:
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>
class Shape {
public:
private:
public:
cout << "Rectangle: Length = " << length << ", Breadth = " << breadth << endl;
};
private:
cout << "Triangle: Base = " << base << ", Height = " << height << endl;
};
int main() {
rect.printData();
tri.printData();
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>
class Employee {
protected:
string name;
int empNo;
string department;
public:
void getInfo() {
getline(cin, department);
void writeInfo() {
};
protected:
double salary;
double bonus;
public:
void getInfo() {
Employee::getInfo();
calculateBonus();
void writeInfo() {
Employee::writeInfo();
void calculateBonus() {
};
private:
int shares;
public:
void getInfo() {
Boss::getInfo();
} else {
shares = 0;
void writeInfo() {
Boss::writeInfo();
if (shares > 0) {
} else {
}
}
};
int main() {
CEO ceo;
ceo.getInfo();
ceo.writeInfo();
return 0;
SAMPLE INPUT:
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.
#include <iostream>
int main() {
int a, b;
try {
if (b == 0) {
int result = a / b;
return 0;
OUTPUT
ERROR!
C++
• #include <iostream>
#include <stdexcept>
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.
C++
• #include <iostream>
#include <stdexcept>
int main() {
int arr[] = {1, 2, 3};
int index;
try {
cout << "Enter an index: ";
cin >> index;
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.
C++
• #include <iostream>
#include <stdexcept>
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.
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.
C++
• #include <iostream>
#include <stdexcept>
#include <typeinfo>
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.
C++
#include <iostream>
#include <stdexcept>
#include <new>
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.
T min = arr[0];
min = arr[i];
return min;
int main() {
return 0;
}
OUTPUT:
Minimum integer: 1
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 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.
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.
• 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() {
};
Number temp;
temp.value = -n.value;
return temp;
int main() {
Number num(5);
num.display();
result.display();
return 0;
Output:
Original Value: 5
arguments. CO2-AP
#include <iostream>
void print() {
void print(int a) {
cout << "Two arguments: " << a << " and " << b << endl;
int main() {
print();
print(5);
print(10, 20);
return 0;
Output:
No arguments
One argument: 5
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() {
Number operator-() {
return Number(-value);
};
int main() {
Number num(5);
num.display();
result.display();
return 0;
Output:
Original 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) {
void print(double d) {
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
#include <iostream>
class Shape {
public:
};
private:
double radius;
public:
Circle(double r) : radius(r) {}
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();
return 0;
Output:
Area: 78.5
7. Write a C++ program for swapping two integers, floating point values using function
Overloading.
#include <iostream>
int temp = a;
a = b;
b = temp;
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;
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
unit-4
#include <iostream>
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; }
};
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
#include <iostream>
#include <string>
class Student {
protected:
int rollNo;
string name;
public:
void getStudentInfo() {
cin.ignore();
getline(cin, name);
}
};
class Marks {
protected:
int marks[3];
public:
void getMarks() {
cout << "Enter marks for subject " << i+1 << ": ";
};
public:
void calculateResult() {
int total = 0;
total += marks[i];
};
int main() {
Result student;
student.getStudentInfo();
student.getMarks();
student.calculateResult();
return 0;
Output:
Student Details:
Roll No: 12
Name: john
class A {
public:
int a;
A() { a = 10; }
};
public:
int b;
B() { b = 20; }
};
public:
int c;
C() { c = 30; }
};
public:
int d;
D() { d = 40; }
};
int main() {
D obj;
cout << "a = " << obj.a << endl; // Only one copy of 'a' exists
return 0;
Output
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>
class PersonalDetails {
protected:
string name;
int age;
string address;
public:
void getPersonalDetails() {
getline(cin, name);
cin.ignore();
getline(cin, address);
};
private:
string grade;
public:
void getGrade() {
void displayDetails() {
};
int main() {
Student student;
student.getPersonalDetails();
student.getGrade();
student.displayDetails();
return 0;
Output:
Enter age: 15
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>
class Employee {
protected:
string name;
int age;
string address;
public:
void getEmployeeDetails() {
getline(cin, name);
cin.ignore();
getline(cin, address);
};
private:
string designation;
double salary;
public:
void getDepartmentDetails() {
getline(cin, designation);
void displayDetails() {
};
int main() {
Department emp;
emp.getEmployeeDetails();
emp.getDepartmentDetails();
emp.displayDetails();
return 0;
}
Output:
Enter age: 45
Enter address: aa
Employee Details:
Name: john
Age: 45
Address: aa
Designation: sales
Salary: $70000
7 Develop a C++ program to get a number from a user using virtual base class.
#include <iostream>
public:
};
protected:
int number;
public:
};
public:
};
public:
cout << "The number you entered is: " << number << endl;
};
int main() {
NumberDisplay nd;
nd.getInput();
nd.showInput();
return 0;
Output
Enter a number: 5
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>
class Shape {
public:
};
private:
double radius;
public:
Circle(double r) : radius(r) {}
};
private:
public:
};
int main() {
Circle c(5);
return 0;
Output:
Area of circle: 78.5
Area of rectangle: 24
UNIT - V
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>
T add(T a, T b) {
return a + b;
int main() {
cout << "Sum of doubles: " << add(3.14, 2.5) << endl;
return 0;
output:
Sum of integers: 8
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>
if (size == 0) {
T min = arr[0];
min = arr[i];
return min;
int main() {
int intArr[] = {5, 2, 8, 1, 9};
cout << "Minimum in int array: " << findMin(intArr, 5) << endl;
cout << "Minimum in double array: " << findMin(doubleArr, 4) << endl;
return 0;
Output:
4 Write a C++ program to handle a single try, catch exceptions for your own problem
situation. CO2-AP
#include <iostream>
#include <stdexcept>
if (b == 0) {
return a / b;
int main() {
try {
return 0;
Output
Enter numerator: 9
5 Develop a C++ program to design a simple calculator using class template CO2-AP
#include <iostream>
class Calculator {
private:
T num1, num2;
public:
T divide() {
if (num2 == 0) {
};
int main() {
try {
return 0;
Output:
Integer calculations:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Double calculations:
Addition: 10
Subtraction: 5
Multiplication: 18.75
Division: 3
#include <iostream>
using namespace std;
T addNumbers(T a, T b) {
return a + b;
int main() {
cout << "Sum of integers: " << addNumbers(int1, int2) << endl;
cout << "Sum of doubles: " << addNumbers(double1, double2) << endl;
return 0;
Output
Sum of integers: 15
7 Write down the syntax for Multiple catch statement. Give an example. CO1-U
try {
Eg:
#include <iostream>
#include <stdexcept>
if (value < 0) {
} else if (value == 0) {
int main() {
try {
checkValue(-5);
cout << "Out of range error: " << e.what() << endl;
} catch (...) {
return 0;
Output:
ERROR!
8 Develop a C++ program for illustrating array index out of bound exception.
#include <iostream>
#include <stdexcept>
int main() {
int index;
try {
cout << "Value at index " << index << " is: " << arr[index] << endl;
return 0;
Output:
ERROR!
Part B
Unit 3
1.Write a C++ program to swap two integers, floats, characters and two strings
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;
}
#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);
};
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
#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";
}
}
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;
}
Ii)Write a C++ program to find the sum of two integers, two floating point values
#include <iostream>
return a + b;
return a + b;
return a + b + c;
int main() {
cout << "Sum of two integers (" << int1 << ", " << int2 << "): "
cout << "Sum of two floating-point values (" << double1 << ", " << double2 << "): "
cout << "Sum of three integers (" << int1 << ", " << int2 << ", " << int3 << "): "
return 0;
}
Output
#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;
}
}
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();
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
#include <iostream>
class Complex {
private:
float real;
float imag;
public:
void display() {
cout << real << " + " << imag << "i" << endl;
};
int main() {
sum.display();
diff.display();
return 0;
output
Sum: 5 + 7i
Difference: 2 + -2i
Syntax:
Return_Type classname :: operator op(Argument list)
{
Function Body
} // This can be done by declaring the function
Here,
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
}
...
};
#include <iostream>
class Number {
private:
int value;
public:
Number(int v = 0) {
value=v;
void display() {
Number operator-() {
return Number(-value);
};
int main() {
Number num(5);
num.display();
result.display();
return 0;
Output:
Original Value: 5
8 How will you overload binary operators using friend functions? Explain with
9.
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 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.
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) {}
int main() {
Complex c1(3.0, 4.0);
return 0;
}
Output
go
Copy code
Original: 3 + 4i
Negation: -3 + -4i
After Increment: 4 + 5i
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) {}
int main() {
Complex c1(3.0, 4.0);
Complex c2(1.5, 2.5);
return 0;
}
Addition: 4.5 + 6.5i
Subtraction: 1.5 + 1.5i
Summary
Operator overloading enhances the readability and usability of your code, allowing you to
use standard operators with user-defined types seamlessly.
Unit-4
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
input/output its data. Write a main function to test the book and tape classes.
ALGORITHM:
PROGRAM:
#include <iostream>
#include <string>
class Publication {
public:
string title;
double price;
void getdata(){
Publication::getdata();
cout << "Enter number of pages: ";
cin >> pages;
}
void putdata() {
Publication::putdata();
cout << "Pages: " << pages << endl;
}
};
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;
return 0;
}
SAMPLE INPUT:
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
ALGORITHM:
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;
}
}
};
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:
SAMPLE OUTPUT:
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
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;
}
}
};
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:
SAMPLE OUTPUT:
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
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
cpp
Copy code
#include <iostream>
#include <cmath>
public:
Triangle(double b, double h) : base(b), height(h) {}
int main() {
// Create objects for Circle and Triangle
Shape* circle = new Circle(5.0);
Shape* triangle = new Triangle(4.0, 3.0);
// 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.
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
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;
}
};
void WriteInfo() {
Employee::WriteInfo();
cout << "Bonus: " << bonus << endl;
}
};
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:
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.
#include <iostream>
if (denominator == 0) {
throw runtime_error("Division by zero is not allowed.");
if (denominator == 0.0) {
int main() {
try {
cout << "Integer Division: " << divide(intNumerator, intDenominator) << endl;
cout << "Floating Point Division: " << divide(floatNumerator, floatDenominator) << endl;
cout << "Error: " << e.what() << endl; // Handle the division by zero error
return 0;
}
Output:
exception.
#include <iostream>
try {
if (denominator == 0) {
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: