0% found this document useful (0 votes)
12 views93 pages

OOPS Practical

The document contains practical exercises on classes and methods in C++, including the design of Employee and Student classes with methods for input and display, as well as friend functions for various operations like calculating areas and adding complex numbers. It also covers method overloading, static variables, and operator overloading. Each section includes code examples demonstrating the concepts discussed.

Uploaded by

ravanyt21
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)
12 views93 pages

OOPS Practical

The document contains practical exercises on classes and methods in C++, including the design of Employee and Student classes with methods for input and display, as well as friend functions for various operations like calculating areas and adding complex numbers. It also covers method overloading, static variables, and operator overloading. Each section includes code examples demonstrating the concepts discussed.

Uploaded by

ravanyt21
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/ 93

Practical 1: Classes and Methods

Q.1 Design an employee class for reading and displaying the employee
information, the getInfo() and displayInfo() methods will be used
respectively where getinfo() will be private method.
Code:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Employee
{
private:
char name[50];
int age;
double salary;

void getInfo()
{
clrscr();

cout << "Enter Employee Name: ";


gets(name);

cout << "Enter Employee Age: ";


cin >> age;

cout << "Enter Employee Salary: ";


cin >> salary;
}

public:
void displayInfo()
{
getInfo();
clrscr();
cout << "\nEmployee information:\n";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Salary: $" << salary << endl;

getch();
}
};

void main()
{
Employee emp;
emp.displayInfo();
getch();
}

Q.2 Design the class student containing getData() and displayData() as


two of its methods which will be used for reading and displaying the
student information respectively. Where getData() will be private
method.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
class Student
{
private:
char name[50];
int age;
double grade;

void getInfo()
{
clrscr();

cout << "Enter Student Name: ";


gets(name);

cout << "Enter Student Age: ";


cin >> age;

cout << "Enter Student Grade: ";


cin >> grade;
}

public:
void displayInfo()
{
getInfo();
clrscr();
cout << "\nEmployee information:\n";
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;

getch();
}
};

void main()
{
Student student;
student.displayInfo();
getch();
}

Q.3 Design the class Demo which will contain the following methods:
readNo(), factorial() for calculating the factorial of a number,
reverseNo() will reverse the given number, isPalindrome() will check
the given number is palindrome, isArmstrong() which will calculate
the given number is armStrong or not.Where readNo() will be private
method.

Q.4 Write a program to demonstrate function definition outside class


and accessing class members in function definition
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

class MyClass
{
private:
int privateVar;

public:
// Constructor
MyClass()
{
privateVar = 0;
}
// Member function declaration
void setPrivateVar(int value);

void displayPrivateVar();
};

// Member function definition outside the class


void MyClass::setPrivateVar(int value)
{
privateVar = value;
}

void MyClass::displayPrivateVar()
{
cout << "Private Variable: " << privateVar << endl;
}

int main()
{
// Create an instance of the MyClass
MyClass myObject;
// Access class members using member functions
myObject.setPrivateVar(42);
myObject.displayPrivateVar();

getch(); // Wait for a key press


return 0;
}
Practical no 2: Using friend functions.

Q.1 Write a friend function for calculate the area of circle, using a single
class
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

const float PI = 3.14159;

// Forward declaration of Circle class


class Circle;

// Friend function declaration


float calculateArea(const Circle& c);

class Circle {
private:
float radius;

public:
// Constructor
Circle(float r) : radius(r) {}
// Accessor function for radius
float getRadius() const {
return radius;
}

// Friend function is declared as a friend inside the class


friend float calculateArea(const Circle& c);
};

// Friend function definition for calculating the area of a circle


float calculateArea(const Circle& c) {
// Access the private member radius of the Circle class
float area = PI * c.radius * c.radius;
return area;
}

int main() {
// Create an instance of the Circle class
Circle myCircle(5.0);

clrscr(); // Clear the screen


// Display the radius
cout << "Radius of the circle: " << myCircle.getRadius() << endl;

// Use the friend function to calculate and display the area


cout << "Area of the circle: " << calculateArea(myCircle) << endl;

getch(); // Wait for a key press


return 0;
}

Q.2 Write a friend function for adding the two complex numbers, using
a single class
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

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

// Friend function declaration


friend Complex addComplex(const Complex& c1, const Complex&
c2);

// Display the complex number


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

// Friend function definition for adding two complex numbers


Complex addComplex(const Complex& c1, const Complex& c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
int main() {
// Create two complex numbers
Complex complex1(2.5, 3.0);
Complex complex2(1.5, 2.5);

// Display the original complex numbers


clrscr(); // Clear the screen
cout << "Original Complex Numbers:\n";
complex1.display();
complex2.display();

// Use the friend function to add complex numbers


Complex sum = addComplex(complex1, complex2);

// Display the result


cout << "\nSum of Complex Numbers:\n";
sum.display();

getch(); // Wait for a key press


return 0;
}
Q.3 Write a friend function for adding the two different distances and
display its sum using two classes.
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

class SumDistance; // Forward declaration

class Distance {
private:
int feet;
float inches;

public:
// Constructor
Distance(int f, float in) : feet(f), inches(in) {}

// Friend function declaration


friend SumDistance addDistances(const Distance& d1, const
Distance& d2);

// Display the distance


void display() {
cout << "Distance: " << feet << " feet " << inches << " inches" <<
endl;
}
};

class SumDistance {
private:
int feet;
float inches;

public:
// Constructor
SumDistance() : feet(0), inches(0.0) {}

// Friend function declaration


friend SumDistance addDistances(const Distance& d1, const
Distance& d2);

// Display the sum distance


void display() {
cout << "Sum Distance: " << feet << " feet " << inches << " inches"
<< endl;
}
};

// Friend function definition for adding two different distances


SumDistance addDistances(const Distance& d1, const Distance& d2) {
SumDistance result;

// Add the feet and inches separately


result.feet = d1.feet + d2.feet;
result.inches = d1.inches + d2.inches;

// If the sum of inches exceeds 12, adjust feet and inches


if (result.inches >= 12.0) {
result.inches -= 12.0;
result.feet++;
}

return result;
}

int main() {
// Create two Distance objects
Distance distance1(3, 6.5);
Distance distance2(2, 8.3);

// Use the friend function to add distances


SumDistance sum = addDistances(distance1, distance2);

// Display the original distances


clrscr(); // Clear the screen
cout << "Distance 1: ";
distance1.display();
cout << "Distance 2: ";
distance2.display();

// Display the sum of distances


cout << "\nSum of Distances:\n";
sum.display();

getch(); // Wait for a key press


return 0;
}
Q4. Write a friend function for adding the two matrix from two
different classes and display its sum.
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

const int MAX_ROWS = 3;


const int MAX_COLS = 3;

class Matrix; // Forward declaration

class SumMatrix {
private:
int matrix[MAX_ROWS][MAX_COLS];

public:
// Friend function declaration
friend SumMatrix addMatrices(const Matrix& m1, const Matrix&
m2);

// Display the sum matrix


void display();
};
class Matrix {
private:
int matrix[MAX_ROWS][MAX_COLS];

public:
// Friend function declaration
friend SumMatrix addMatrices(const Matrix& m1, const Matrix&
m2);

// Input matrix elements


void inputMatrix();

// Display the matrix


void display();
};

// Friend function definition for adding two matrices


SumMatrix addMatrices(const Matrix& m1, const Matrix& m2) {
SumMatrix result;

// Add the corresponding elements of matrices m1 and m2


for (int i = 0; i < MAX_ROWS; ++i) {
for (int j = 0; j < MAX_COLS; ++j) {
result.matrix[i][j] = m1.matrix[i][j] + m2.matrix[i][j];
}
}

return result;
}

// Display the sum matrix


void SumMatrix::display() {
cout << "Sum Matrix:\n";
for (int i = 0; i < MAX_ROWS; ++i) {
for (int j = 0; j < MAX_COLS; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

// Input matrix elements


void Matrix::inputMatrix() {
cout << "Enter matrix elements (3x3):\n";
for (int i = 0; i < MAX_ROWS; ++i) {
for (int j = 0; j < MAX_COLS; ++j) {
cout << "Enter element at position [" << i << "][" << j << "]: ";
cin >> matrix[i][j];
}
}
}

// Display the matrix


void Matrix::display() {
cout << "Matrix:\n";
for (int i = 0; i < MAX_ROWS; ++i) {
for (int j = 0; j < MAX_COLS; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

int main() {
// Create two Matrix objects
Matrix matrix1, matrix2;

// Input matrix elements for both matrices


clrscr(); // Clear the screen
cout << "Matrix 1:\n";
matrix1.inputMatrix();
cout << "\nMatrix 2:\n";
matrix2.inputMatrix();

// Use the friend function to add matrices


SumMatrix sum = addMatrices(matrix1, matrix2);

// Display the original matrices


cout << "\nOriginal Matrices:\n";
matrix1.display();
matrix2.display();

// Display the sum of matrices


cout << "\nSum of Matrices:\n";
sum.display();

getch(); // Wait for a key press


return 0;
}
Practical no 3: Constructors and method overloading.
Q.1 Design a class Complex for adding the two complex numbers and
also show the use of constructor.
Code:
//Design a class Complex for adding the two complex numbers and also
show the use of constructor.

#include <iostream.h>
#include <conio.h>

class Complex {
private:
float real;
float imag;

public:
// Constructor with default values
Complex(float r = 0.0, float i = 0.0) : real(r), imag(i) {}

// Member function to add two complex numbers


Complex add(const Complex& other) const {
Complex result;
result.real = real + other.real;
result.imag = imag + other.imag;
return result;
}

// Display the complex number


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

int main() {
// Create two instances of the Complex class using the constructor
Complex complex1(2.5, 3.0);
Complex complex2(1.5, 2.5);

clrscr(); // Clear the screen

// Display the original complex numbers


cout << "Original Complex Numbers:\n";
complex1.display();
complex2.display();
// Use the add function to add complex numbers
Complex sum = complex1.add(complex2);

// Display the result


cout << "\nSum of Complex Numbers:\n";
sum.display();

getch(); // Wait for a key press


return 0;
}

Q.2 Design a class Geometry containing the methods area() and


volume() and also overload the area() function.
#include <iostream.h>
#include <conio.h>

class Geometry {
public:
// Calculate area for 2D shapes (default implementation)
float area() const {
return 0.0;
}
// Calculate volume for 3D shapes (default implementation)
float volume() const {
return 0.0;
}
};

// Overload area() for a rectangle


class Rectangle : public Geometry {
private:
float length;
float width;

public:
Rectangle(float l, float w) : length(l), width(w) {}

// Overloaded area() for a rectangle


float area() const {
return length * width;
}
};
// Overload area() for a circle
class Circle : public Geometry {
private:
float radius;

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

// Overloaded area() for a circle


float area() const {
return 3.14159 * radius * radius;
}
};

int main() {
clrscr(); // Clear the screen

// Create objects of different shapes


Rectangle rectangle(4.0, 5.0);
Circle circle(3.0);

// Display areas using the default area() from Geometry


cout << "Default Area (Geometry class):\n";
cout << "Rectangle: " << rectangle.area() << endl;
cout << "Circle: " << circle.area() << endl;

// Display areas using the overloaded area() functions


cout << "\nOverloaded Area:\n";
cout << "Rectangle: " << rectangle.area() << endl;
cout << "Circle: " << circle.area() << endl;

getch(); // Wait for a key press


return 0;
}

Q.3 Design a class Static Demo to show the implementation of static


variable and static function.
Code:
#include <iostream.h>
#include <conio.h>

class StaticDemo {
private:
int instanceVariable;
static int staticVariable; // Static variable shared among all instances

public:
// Constructor to initialize instanceVariable
StaticDemo(int value) : instanceVariable(value) {}

// Static function to modify the static variable


static void modifyStaticVariable(int value) {
staticVariable = value;
}

// Display the values of instanceVariable and staticVariable


void display() const {
cout << "Instance Variable: " << instanceVariable << endl;
cout << "Static Variable: " << staticVariable << endl;
}
};

// Initialization of static variable


int StaticDemo::staticVariable = 0;

int main() {
clrscr(); // Clear the screen

// Create two objects of StaticDemo class


StaticDemo obj1(10);
StaticDemo obj2(20);

// Display initial values


cout << "Initial Values:\n";
obj1.display();
obj2.display();

// Modify the static variable using the static function


StaticDemo::modifyStaticVariable(100);

// Display values after modifying the static variable


cout << "\nValues after modifying static variable:\n";
obj1.display();
obj2.display();

getch(); // Wait for a key press


return 0;
}
Practical no 4: Operator Overloading.
Q.1 Overload the operator unary(-) for demonstrating operator
overloading.
Code:
#include <iostream.h>
#include <conio.h>

class MyNumber {
private:
int value;

public:
// Constructor
MyNumber(int val) : value(val) {}

// Overload unary - operator


MyNumber operator-() const {
return MyNumber(-value);
}

// Display the value


void display() const {
cout << "Value: " << value << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create an object of MyNumber class


MyNumber num1(10);

// Display original value


cout << "Original Value:\n";
num1.display();

// Use the overloaded unary - operator


MyNumber num2 = -num1;

// Display the negated value


cout << "\nNegated Value:\n";
num2.display();

getch(); // Wait for a key press


return 0;
}

Q.2 Overload the operator + for adding the timings of two clocks, And
also pass objects as an argument
Code:
#include <iostream.h>
#include <conio.h>

class Clock {
private:
int hours;
int minutes;
int seconds;

public:
// Constructor
Clock(int h, int m, int s) : hours(h), minutes(m), seconds(s) {}

// Overload + operator to add two Clock objects


Clock operator+(const Clock& other) const {
int totalSeconds = seconds + other.seconds + 60 * (minutes +
other.minutes) + 3600 * (hours + other.hours);
int newHours = totalSeconds / 3600;
int remainingSeconds = totalSeconds % 3600;
int newMinutes = remainingSeconds / 60;
int newSeconds = remainingSeconds % 60;

return Clock(newHours, newMinutes, newSeconds);


}

// Display the time


void display() const {
cout << "Time: " << hours << " hours, " << minutes << " minutes, "
<< seconds << " seconds" << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create two Clock objects


Clock time1(2, 30, 45);
Clock time2(1, 45, 20);

// Display original timings


cout << "Time 1:\n";
time1.display();
cout << "\nTime 2:\n";
time2.display();

// Use the overloaded + operator to add timings


Clock sum = time1 + time2;

// Display the sum of timings


cout << "\nSum of Timings:\n";
sum.display();

getch(); // Wait for a key press


return 0;
}

Q.3 Overload the + for concatenating the two strings. For e.g “Py” +
“thon” = Python
Code:
#include <iostream.h>
#include <string.h>
#include <conio.h>
#include <stdio.h>

class MyString {
private:
char* str;

public:
// Constructor
MyString(const char* s) {
str = new char[strlen(s) + 1];
strcpy(str, s);
}

// Overload + operator for string concatenation


MyString operator+(const MyString& other) const {
char* result = new char[strlen(str) + strlen(other.str) + 1];
strcpy(result, str);
strcat(result, other.str);

return MyString(result);
}
// Display the string
void display() const {
cout << "String: " << str << endl;
}

// Destructor to free memory


~MyString() {
delete[] str;
}
};

int main() {
clrscr(); // Clear the screen

// Create two MyString objects


MyString str1("Py");
MyString str2("thon");

// Display original strings


cout << "String 1:\n";
str1.display();
cout << "\nString 2:\n";
str2.display();

// Use the overloaded + operator to concatenate strings


MyString result = str1 + str2;

// Display the concatenated string


cout << "\nConcatenated String:\n";
result.display();

getch(); // Wait for a key press


return 0;
}
Practical 5: Exception Handling
Q.1 Write a C++ program that takes two integer inputs from the user,
representing a dividend and a divisor. The program should then
perform the division operation and print the result. However, if the
divisor is zero, the program should throw an exception with the
message "Division by zero error!" and handle it using exception
handling.
Code:
#include <iostream.h>
#include <conio.h>

int main() {
clrscr();

int dividend, divisor;


cout << "Enter dividend: ";
cin >> dividend;
cout << "Enter divisor: ";
cin >> divisor;

try {
if (divisor == 0) {
throw "Division by zero error!";
}
int result = dividend / divisor;
cout << "Result of division: " << result << endl;
} catch (const char* error) {
cout << "Error: " << error << endl;
}

getch();
return 0;
}

Q.2 Write a C++ program that initializes an array of integers with 5


elements. The program should prompt the user to enter an index to
access an element from the array. After the user enters the index, the
program should attempt to access the corresponding element in the
array. However, if the entered index is out of range (less than 0 or
greater than or equal to 5), the program should throw an exception
with the message "Index out of range!" and handle it using exception
handling.
Code:
#include <iostream.h>
#include <conio.h>
int main() {
clrscr();

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


int index;
cout << "Enter index to access element: ";
cin >> index;

try {
if (index < 0 || index >= 5) {
throw "Index out of range!";
}
cout << "Element at index " << index << ": " << arr[index] << endl;
} catch (const char* error) {
cout << "Error: " << error << endl;
}

getch();
return 0;
}
Q.3 Write a C++ program that attempts to open a file named
"nonexistent.txt" for reading. If the file does not exist, the program
should throw an exception with the message "Failed to open file!" and
handle it using exception handling.
Code:
#include <iostream.h>
#include <conio.h>
#include <fstream.h>

int main() {
clrscr();

try {
ifstream file("nonexistent.txt");
if (!file) {
throw "Failed to open file!";
}
cout << "File opened successfully." << endl;
} catch (const char* error) {
cout << "Error: " << error << endl;
}

getch();
return 0;
}

Q.4 Write a C++ program that throws a custom exception of type


CustomException with the message "Custom exception occurred!". The
program should then catch the exception and handle it using exception
handling.
Code:
#include <iostream.h>
#include <conio.h>

class CustomException {
public:
const char* message;
CustomException(const char* msg) : message(msg) {}
};

int main() {
clrscr();

try {
throw CustomException("Custom exception occurred!");
} catch (CustomException& e) {
cout << "Error: " << e.message << endl;
}

getch();
return 0;
}

Q.5 Write a C++ program that prompts the user to enter an index to
access an element from an array and a divisor for a division operation.
The program should perform both operations and handle any
exceptions that may occur.
a.If the entered index is out of range (less than 0 or greater than or
equal to 5), the program should throw an exception with the message
"Index out of range!" and handle it using exception handling.
b.If the divisor is zero, the program should throw an exception with the
message "Division by zero error!" and handle it using exception
handling.
c.Additionally, the program should have a catch-all block to handle any
other types of exceptions and print "Unknown error occurred."
Code:
#include <iostream.h>
#include <conio.h>

int main() {
clrscr();

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


int index, divisor;

cout << "Enter index to access element: ";


cin >> index;
cout << "Enter divisor: ";
cin >> divisor;

try {
if (index < 0 || index >= 5) {
throw "Index out of range!";
}
cout << "Element at index " << index << ": " << arr[index] << endl;

if (divisor == 0) {
throw "Division by zero error!";
}
cout << "Result of division: " << arr[0] / divisor << endl;

} catch (const char* error) {


cout << "Error: " << error << endl;
} catch (...) {
cout << "Unknown error occurred." << endl;
}

getch();
return 0;
}
Practical 6: Inheritance-I
Q.1 Design a class for single level inheritance.
Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Base class
class Animal {
protected:
char name[50];

public:
Animal(const char* animalName) {
strcpy(name, animalName);
}

void eat() {
cout << name << " is eating." << endl;
}

void sleep() {
cout << name << " is sleeping." << endl;
}
};

// Derived class
class Dog : public Animal {
public:
Dog(const char* dogName) : Animal(dogName) {}

void bark() {
cout << name << " is barking." << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create an instance of the base class


Animal genericAnimal("Generic Animal");
genericAnimal.eat();
genericAnimal.sleep();
cout << endl;

// Create an instance of the derived class


Dog myDog("Buddy");
myDog.eat(); // Inherited from the base class
myDog.sleep(); // Inherited from the base class
myDog.bark(); // Specific to the derived class

getch(); // Wait for a key press


return 0;
}

Q.2 Design a class for multiple inheritance.


Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

// First base class


class Animal {
protected:
char name[50];

public:
Animal(const char* animalName) {
strcpy(name, animalName);
}

void eat() {
cout << name << " is eating." << endl;
}

void sleep() {
cout << name << " is sleeping." << endl;
}
};

// Second base class


class Machine {
protected:
char machineType[50];
public:
Machine(const char* type) {
strcpy(machineType, type);
}

void start() {
cout << machineType << " is starting." << endl;
}

void stop() {
cout << machineType << " is stopping." << endl;
}
};

// Derived class inheriting from both Animal and Machine


class Robot : public Animal, public Machine {
public:
Robot(const char* robotName, const char* robotType)
: Animal(robotName), Machine(robotType) {}

void work() {
cout << name << " the " << machineType << " is working." << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create an instance of the derived class


Robot robot("Robo", "Industrial Robot");

// Access methods from both base classes


robot.eat(); // From Animal
robot.sleep(); // From Animal
robot.start(); // From Machine
robot.stop(); // From Machine
robot.work(); // Specific to the derived class

getch(); // Wait for a key press


return 0;
}
Q.3 Design a class for multilevel inheritance
Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Base class
class Animal {
protected:
char name[50];

public:
Animal(const char* animalName) {
strcpy(name, animalName);
}

void eat() {
cout << name << " is eating." << endl;
}
void sleep() {
cout << name << " is sleeping." << endl;
}
};

// First derived class


class Mammal : public Animal {
public:
Mammal(const char* mammalName) : Animal(mammalName) {}

void giveBirth() {
cout << name << " is giving birth." << endl;
}
};

// Second derived class


class Dog : public Mammal {
public:
Dog(const char* dogName) : Mammal(dogName) {}

void bark() {
cout << name << " is barking." << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create an instance of the most derived class


Dog myDog("Buddy");

// Access methods from all levels of inheritance


myDog.eat(); // From Animal
myDog.sleep(); // From Animal
myDog.giveBirth(); // From Mammal
myDog.bark(); // Specific to the derived class

getch(); // Wait for a key press


return 0;
}
Practical 7: Inheritance-II

Q.1 Implement the hierarchical inheritance


Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Base class
class Animal {
protected:
char name[50];

public:
Animal(const char* animalName) {
strcpy(name, animalName);
}

void eat() {
cout << name << " is eating." << endl;
}
void sleep() {
cout << name << " is sleeping." << endl;
}
};

// First derived class


class Dog : public Animal {
public:
Dog(const char* dogName) : Animal(dogName) {}

void bark() {
cout << name << " is barking." << endl;
}
};

// Second derived class


class Cat : public Animal {
public:
Cat(const char* catName) : Animal(catName) {}

void meow() {
cout << name << " is meowing." << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create an instance of the first derived class


Dog myDog("Buddy");
myDog.eat(); // From Animal
myDog.sleep(); // From Animal
myDog.bark(); // Specific to the first derived class

cout << endl;

// Create an instance of the second derived class


Cat myCat("Whiskers");
myCat.eat(); // From Animal
myCat.sleep(); // From Animal
myCat.meow(); // Specific to the second derived class

getch(); // Wait for a key press


return 0;
}

Q.2 Implement the Hybrid inheritance.


Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Base class
class Animal {
protected:
char name[50];

public:
Animal(const char* animalName) {
strcpy(name, animalName);
}

void eat() {
cout << name << " is eating." << endl;
}
void sleep() {
cout << name << " is sleeping." << endl;
}
};

// First derived class (Hierarchical Inheritance)


class Dog : public Animal {
public:
Dog(const char* dogName) : Animal(dogName) {}

void bark() {
cout << name << " is barking." << endl;
}
};

// Second derived class (Hierarchical Inheritance)


class Cat : public Animal {
public:
Cat(const char* catName) : Animal(catName) {}

void meow() {
cout << name << " is meowing." << endl;
}
};

// Third derived class (Multiple Inheritance)


class Robot {
protected:
char robotName[50];

public:
Robot(const char* robotName) {
strcpy(this->robotName, robotName);
}

void work() {
cout << robotName << " is working." << endl;
}
};

// Fourth derived class (Hybrid Inheritance)


class RoboDog : public Dog, public Robot {
public:
RoboDog(const char* dogName, const char* robotName)
: Dog(dogName), Robot(robotName) {}

void guard() {
cout << Dog::name << " the RoboDog is guarding." << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create an instance of the hybrid derived class


RoboDog myRoboDog("Buddy", "RoboBuddy");
myRoboDog.eat(); // From Animal (Hierarchical Inheritance)
myRoboDog.sleep(); // From Animal (Hierarchical Inheritance)
myRoboDog.bark(); // Specific to the first derived class (Hierarchical
Inheritance)
myRoboDog.work(); // From Robot (Multiple Inheritance)
myRoboDog.guard(); // Specific to the fourth derived class (Hybrid
Inheritance)

getch(); // Wait for a key press


return 0;
}
Q.3 Program on inheritance using public, private and protected type
derivation.
Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Base class
class Base {
public:
int publicVar;

Base() : publicVar(0) {}

void publicFunction() {
cout << "Public function in Base class." << endl;
}

protected:
int protectedVar;

void protectedFunction() {
cout << "Protected function in Base class." << endl;
}

private:
int privateVar;

void privateFunction() {
cout << "Private function in Base class." << endl;
}
};

// Derived class with public inheritance


class PublicDerived : public Base {
public:
void accessBaseMembers() {
cout << "Accessing Base class members in PublicDerived class." <<
endl;
publicVar = 1; // Accessible
protectedVar = 2; // Accessible
// privateVar is not accessible
publicFunction(); // Accessible
protectedFunction(); // Accessible
// privateFunction() is not accessible
}
};

// Derived class with protected inheritance


class ProtectedDerived : protected Base {
protected:
void accessBaseMembers() {
cout << "Accessing Base class members in ProtectedDerived class."
<< endl;
publicVar = 1; // Accessible
protectedVar = 2; // Accessible
// privateVar is not accessible
publicFunction(); // Accessible
protectedFunction(); // Accessible
// privateFunction() is not accessible
}
};

// Derived class with private inheritance


class PrivateDerived : private Base {
private:
void accessBaseMembers() {
cout << "Accessing Base class members in PrivateDerived class." <<
endl;
publicVar = 1; // Accessible
protectedVar = 2; // Accessible
// privateVar is not accessible
publicFunction(); // Accessible
protectedFunction(); // Accessible
// privateFunction() is not accessible
}
};

int main() {
clrscr(); // Clear the screen

// Example of public inheritance


PublicDerived publicDerivedObj;
publicDerivedObj.accessBaseMembers();

// Example of protected inheritance


ProtectedDerived protectedDerivedObj;
// protectedDerivedObj.accessBaseMembers(); // Error: Access is
protected
// Example of private inheritance
PrivateDerived privateDerivedObj;
// privateDerivedObj.accessBaseMembers(); // Error: Access is
private

getch(); // Wait for a key press


return 0;
}
Practical 8: Virtual functions and abstract classes
Q.1 Implement the concept of method overriding.
Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

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

// Derived class
class Derived : public Base {
public:
// Overriding the show() method of the Base class
void show() {
cout << "Derived class show() function" << endl;
}
};

int main() {
clrscr(); // Clear the screen

Base baseObj;
Derived derivedObj;

// Call the show() function of Base class


baseObj.show(); // Output: Base class show() function

// Call the show() function of Derived class


derivedObj.show(); // Output: Derived class show() function

getch(); // Wait for a key press


return 0;
}

Q.2 Show the use of virtual function


Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

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

// Derived class
class Derived : public Base {
public:
// Overriding the show() method of the Base class
void show() {
cout << "Derived class show() function" << endl;
}
};

int main() {
clrscr(); // Clear the screen
Base baseObj;
Derived derivedObj;

// Call the show() function of Base class


baseObj.show(); // Output: Base class show() function

// Call the show() function of Derived class


derivedObj.show(); // Output: Derived class show() function

// Call the show() function of Deriverd class using base class pointer
Base* basePtr = &derivedObj;
basePtr->show(); //Output: Derived class show() function

getch(); // Wait for a key press


return 0;
}

Q.3 Show the implementation of abstract class.


Code:
#include <iostream.h>
#include <conio.h>
#include <string.h>

// Abstract base class


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

// Derived class 1: Rectangle


class Rectangle : public Shape {
private:
float length;
float width;

public:
Rectangle(float l, float w) : length(l), width(w) {}

// Implementation of the pure virtual function


float area() {
return length * width;
}
};

// Derived class 2: Circle


class Circle : public Shape {
private:
float radius;

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

// Implementation of the pure virtual function


float area() {
return 3.14 * radius * radius;
}
};

int main() {
clrscr(); // Clear the screen

// Creating objects of derived classes


Rectangle rect(5, 3);
Circle circle(4);

// Calling area() method on objects of derived classes


cout << "Area of Rectangle: " << rect.area() << endl;
cout << "Area of Circle: " << circle.area() << endl;

getch(); // Wait for a key press


return 0;
}
Practical 9: Templates
Q.1 Programs on Function Templates.
1. Maximum of Two Numbers:
Code:
#include <iostream.h>
#include <conio.h>

template <class T>


T max(T a, T b) {
return (a > b) ? a : b;
}

int main() {
clrscr();

int intMax = max(10, 20);


float floatMax = max(10.5f, 20.7f);

cout << "Maximum of 10 and 20: " << intMax << endl;
cout << "Maximum of 10.5 and 20.7: " << floatMax << endl;

getch();
return 0;
}

2. Swap Two Values:


#include <iostream.h>
#include <conio.h>

template <class T>


void swapValues(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}

int main() {
clrscr();

int x = 10, y = 20;


cout << "Before swap: x = " << x << ", y = " << y << endl;
swapValues(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
getch();
return 0;
}

3. Calculate Power:
#include <iostream.h>
#include <conio.h>

template <class T>


T power(T base, int exponent) {
T result = 1;
for (int i = 0; i < exponent; ++i) {
result *= base;
}
return result;
}

int main() {
clrscr();

int intPower = power(2, 3);


float floatPower = power(2.5f, 2);
cout << "2^3 = " << intPower << endl;
cout << "2.5^2 = " << floatPower << endl;

getch();
return 0;
}

Q.2 Programs on Class Templates


1. Pair Class Template:
#include <iostream.h>
#include <conio.h>

// Pair class template


template <class T1, class T2>
class Pair {
private:
T1 first; // First element of the pair
T2 second; // Second element of the pair

public:
// Constructor to initialize the pair with given values
Pair(T1 f, T2 s) : first(f), second(s) {}

// Method to display the pair


void display() {
cout << "(" << first << ", " << second << ")" << endl;
}
};

int main() {
clrscr(); // Clear the screen

// Create a pair of integers and float


Pair<int, float> pair1(10, 3.14f);
pair1.display(); // Display the pair: (10, 3.14)

// Create a pair of character and string


Pair<char, const char*> pair2('a', "Hello");
pair2.display(); // Display the pair: (a, Hello)

getch(); // Wait for a key press


return 0;
}
2.Volume of box
#include <iostream.h>
#include <conio.h>

// Box class template


template <class T>
class Box {
private:
T length;
T width;
T height;

public:
// Constructor to initialize the box dimensions
Box(T l, T w, T h) : length(l), width(w), height(h) {}

// Method to calculate and return the volume of the box


T volume() {
return length * width * height;
}
};
int main() {
clrscr(); // Clear the screen

// Create a box of integers


Box<int> intBox(2, 3, 4);
cout << "Volume of intBox: " << intBox.volume() << endl; // Output:
24

// Create a box of floats


Box<float> floatBox(1.5f, 2.5f, 3.5f);
cout << "Volume of floatBox: " << floatBox.volume() << endl; //
Output: 13.125

getch(); // Wait for a key press


return 0;
}
Practical 10: File handling
Q.1 Design a class FileDemo open a file in read mode and display the
total number of words and lines in the file.
Code:
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <string.h>

class FileDemo {
private:
char filename[100];

public:
FileDemo(const char* fname) {
strcpy(filename, fname);
}

void displayWordAndLineCount() {
ifstream file(filename); // Open the file in read mode
if (!file) {
cout << "Failed to open file!" << endl;
return;
}

int wordCount = 0;
int lineCount = 0;
char buffer[100];

while (!file.eof()) {
file.getline(buffer, 100); // Read a line from the file

if (strlen(buffer) > 0) { // Check if line is not empty


lineCount++;

// Tokenize the line to count words


char* token = strtok(buffer, " ");
while (token != NULL) {
wordCount++;
token = strtok(NULL, " ");
}
}
}
file.close(); // Close the file

cout << "Total words in file: " << wordCount << endl;
cout << "Total lines in file: " << lineCount << endl;
}
};

int main() {
clrscr(); // Clear the screen

FileDemo fileDemo("example.txt");
fileDemo.displayWordAndLineCount();

getch(); // Wait for a key press


return 0;
}

Q.2 Design a class to read and write a file.


Code:
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <string.h>

class FileHandler {
private:
char filename[100];

public:
FileHandler(const char* fname) {
strcpy(filename, fname);
}

void writeFile(const char* content) {


ofstream file(filename); // Open file for writing
if (!file) {
cout << "Failed to open file for writing!" << endl;
return;
}

file << content; // Write content to file


file.close(); // Close the file
cout << "Content successfully written to file." << endl;
}
void readFile() {
ifstream file(filename); // Open file for reading
if (!file) {
cout << "Failed to open file for reading!" << endl;
return;
}

char buffer[100];
while (!file.eof()) {
file.getline(buffer, 100); // Read a line from the file
cout << buffer << endl; // Display the line
}

file.close(); // Close the file


}
};

int main() {
clrscr(); // Clear the screen

FileHandler file("example.txt");
// Write content to file
file.writeFile("Hello, this is a test file.\nIt contains some text.");

// Read content from file


cout << "Content of file:" << endl;
file.readFile();

getch(); // Wait for a key press


return 0;
}

Q.3 Design a class to handle multiple files and file operations


Code:
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <string.h>

class FileManager {
private:
char** filenames;
int numFiles;

public:
FileManager(int num) : numFiles(num) {
filenames = new char*[numFiles];
for (int i = 0; i < numFiles; ++i) {
filenames[i] = new char[100]; // Assuming max filename length is
100
filenames[i][0] = '\0'; // Initialize filename to empty string
}
}

~FileManager() {
for (int i = 0; i < numFiles; ++i) {
delete[] filenames[i]; // Deallocate memory for each filename
}
delete[] filenames; // Deallocate memory for filenames array
}

void setFilename(int index, const char* fname) {


if (index >= 0 && index < numFiles) {
strcpy(filenames[index], fname); // Set filename at specified
index
} else {
cout << "Invalid index!" << endl;
}
}

void displayFilenames() {
cout << "File List:" << endl;
for (int i = 0; i < numFiles; ++i) {
cout << "[" << i << "]: " << filenames[i] << endl; // Display
filenames
}
}

void writeFile(int index, const char* content) {


if (index >= 0 && index < numFiles) {
ofstream file(filenames[index]); // Open file for writing
if (!file) {
cout << "Failed to open file for writing!" << endl;
return;
}
file << content; // Write content to file
file.close(); // Close the file
cout << "Content successfully written to file: " <<
filenames[index] << endl;
} else {
cout << "Invalid index!" << endl;
}
}

void readFile(int index) {


if (index >= 0 && index < numFiles) {
ifstream file(filenames[index]); // Open file for reading
if (!file) {
cout << "Failed to open file for reading!" << endl;
return;
}

char buffer[100];
cout << "Content of file " << filenames[index] << ":" << endl;
while (!file.eof()) {
file.getline(buffer, 100); // Read a line from the file
cout << buffer << endl; // Display the line
}

file.close(); // Close the file


} else {
cout << "Invalid index!" << endl;
}
}
};

int main() {
clrscr(); // Clear the screen

FileManager fileManager(2); // Create FileManager object with


capacity for 2 files
fileManager.setFilename(0, "file1.txt"); // Set filename for first file
fileManager.setFilename(1, "file2.txt"); // Set filename for second file

fileManager.displayFilenames(); // Display list of filenames

// Write content to file 1


fileManager.writeFile(0, "This is content for file 1.");
// Write content to file 2
fileManager.writeFile(1, "This is content for file 2.");

// Read content from file 1


fileManager.readFile(0);

// Read content from file 2


fileManager.readFile(1);

getch(); // Wait for a key press


return 0;
}

You might also like