0% found this document useful (0 votes)
54 views140 pages

Oop Exp 7-17

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

Oop Exp 7-17

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

DEPARTMENT OF COMPUTER ENGINEERING

Subject: OOP Subject Code: 313304

Semester:3th Semester Course: Computer Engineering

Laboratory No: L003A Name of Subject Teacher: Sangeeta


shirsat Mam

Name of Student: Prathamesh Kaduskar Roll Id: 23203C0058

Experiment No: 7

Title of Write program to Implement Friend Function using


Experiment
• Two different classes

• External Function

Pratcical Related Questions:-


1. WAP to declare a class calculation. Display addition, subtraction,
multiplication, division of

two numbers. Use friend function.

#include <iostream>

using namespace std;

class Calculation

{a

private:
float num1, num2;

public:

Calculation(float a, float b) : num1(a), num2(b) {}

friend void performCalculations(Calculation calc);

};

void performCalculations(Calculation calc)

cout << "Addition: " << (calc.num1 + calc.num2) << endl;

cout << "Subtraction: " << (calc.num1 - calc.num2) << endl;

cout << "Multiplication: " << (calc.num1 * calc.num2) << endl;

if (calc.num2 != 0) {

cout << "Division: " << (calc.num1 / calc.num2) << endl;

else

cout << "Division: Cannot divide by zero!" << endl;

int main()

float a, b;

cout << "Enter two numbers: ";

cin >> a >> b;

Calculation calc(a, b);

performCalculations(calc);
return 0;

a) How many member functions are

there in this C++ class excluding

constructors and destructors?

class Box

int capacity;

public:

void print();

friend void show();

bool compare();

friend bool lost();

};

ANS:-

 void print(); - A public member function.


 bool compare(); - Another public member function.
 friend void show(); - A friend function, but not a member function of
the class.
 friend bool lost(); - Another friend function, but not a member function
of the class.

b) What will be the output of the

following C++ code?

#include <iostream>

#include <string>

using namespace std;

class Box

int capacity;

public:

Box(int cap){

capacity = cap;

friend void show();

};

void show()

Box b(10);

cout<<"Value of capacity

is: "<<b.capacity<<endl;

int main(int argc, char const *argv[])


{

show();

return 0;

Exercise:-
1. Write a C++ program to exchange the values of two variables using friend
function.

#include <iostream>

using namespace std;

class Exchange

private:

int a, b;

public:

Exchange(int x, int y) : a(x), b(y) {}

friend void swapValues(Exchange &e);

void display() const

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

};

void swapValues(Exchange &e)

int temp = e.a;

e.a = e.b;

e.b=temp;

int main()a

int x, y;

cout << "Enter two integers: ";

cin >> x >> y;

Exchange e(x, y);

cout << "Before swapping: ";

e.display();

swapValues(e);

cout << "After swapping: ";

e.display();

return 0;

}
2. WAP to create two classes test1 and test2 which stores marks of a
student. Read value for

class objects and calculate average of two tests using friend function.

#include <iostream>

using namespace std;

class Test1;

class Test2;

float calculateAverage(Test1, Test2);

class Test1

private:

float marks1;

public:

void readMarks()

cout << "Enter marks for Test 1: ";

cin >> marks1;


}

friend float calculateAverage(Test1 t1, Test2 t2);

};

class Test2

private:

float marks2;

public:

void readMarks()

cout << "Enter marks for Test 2: ";

cin >> marks2;

friend float calculateAverage(Test1 t1, Test2 t2);

};

float calculateAverage(Test1 t1, Test2 t2) {

return (t1.marks1 + t2.marks2) / 2;

int main() {

Test1 t1;

Test2 t2;

t1.readMarks();

t2.readMarks();

float average = calculateAverage(t1, t2);

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

return 0;
}

Experiment No: 8

Title of Write program to Implement-


Experiment
• Static Data Member

• Static Member Function

Practical Related Questions:-


1.Write a Program to calculate weight of object at different planets using
formula weight=m*g

Where m=mass of object G=gravitational force Declare g as static member


variable.

#include <iostream>

using namespace std;

class WeightCalculator

private:

static float g;
float mass;

public:

WeightCalculator(float m) : mass(m) {}

static void setGravity(float gravity) {

g = gravity;

float calculateWeight() {

return mass * g;

void displayWeight(const string& planetName)

cout << "Weight of the object on " << planetName << ": " <<
calculateWeight() << " N" << endl;

};

float WeightCalculator::g = 0;

int main()

float mass;

cout << "Enter the mass of the object (in kg): ";

cin >> mass;

WeightCalculator obj(mass);

WeightCalculator::setGravity(9.81);

obj.displayWeight("Earth");

WeightCalculator::setGravity(3.71);

obj.displayWeight("Mars");

WeightCalculator::setGravity(24.79);
obj.displayWeight("Jupiter");

WeightCalculator::setGravity(1.62);

obj.displayWeight("Moon");

return 0;

A) Which is correct syntax to access the static member functions with class
name?

ClassName::staticFunctionName();

b)What will be the output of the following

C++ code?

class Test

private: static int x;


public: static void fun()

cout &lt;&lt; ++x

&lt;&lt; “ ”;

};

int Test :: x =20;

void main()

Test x;

x.fun();

x.fun();

c) What will be the output of the following code?

class Test

public: Test()

{
cout &lt;&lt; "Test's

Constructor is Called " &lt;&lt;

endl;

};

class Result

static Test a;

public:

Result()

cout &lt;&lt;

"Result's Constructor is Called "

&lt;&lt; endl;

};

void main()

Result b;

}
Exercise:-
Write a Program to define a class having data members principal, duration
and rate of interest.

Declare rate _of_ interest as static member variable .calculate the simple
interest and display it.

#include <iostream>

using namespace std;

class InterestCalculator

private:

double principal;

int duration;

static double rateOfInterest;

public:

InterestCalculator(double p, int d) : principal(p), duration(d) {}

static void setRateOfInterest(double rate) {

rateOfInterest = rate;

}
double calculateSimpleInterest() {

return (principal * rateOfInterest * duration) / 100;

void displaySimpleInterest()

double simpleInterest = calculateSimpleInterest();

cout << "Simple Interest: " << simpleInterest << endl;

};

double InterestCalculator::rateOfInterest = 0;

int main()

InterestCalculator::setRateOfInterest(5.0);

InterestCalculator calc(10000, 3); Duration = 3 years

calc.displaySimpleInterest();

return 0;

Experiment No: 9

Title of Write programs to create array of objects.


Experiment

Practical Related Questions:-


1. Write a Program to declare a class birthday having data member day,
month and year.

Accept this info for object using pointer to array of object and display it.
#include <iostream>

using namespace std;

class Birthday

private:

int day;

int month;

int year;

public:

void inputBirthday()

cout << "Enter day (1-31): ";

while (!(cin >> day) || day < 1 || day > 31) {

cout << "Invalid input. Please enter a valid day (1-31): ";

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n');

cout << "Enter month (1-12): ";

while (!(cin >> month) || month < 1 || month > 12) {

cout << "Invalid input. Please enter a valid month (1-12): ";

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n');

}
cout << "Enter year (e.g., 2024): ";

while (!(cin >> year) || year < 0)

cout << "Invalid input. Please enter a valid year (>= 0): ";

cin.clear();

cin.ignore(numeric_limits<streamsize>::max(), '\n');

void displayBirthday() const

cout << "Birthday: " << day << "/" << month << "/" << year <<
endl;

};

int main()

int n;

cout << "Enter number of birthdays: ";

cin >> n;

while (n <= 0) {

cout << "Please enter a valid number of birthdays (> 0): ";

cin >> n;

Birthday* birthdays = new Birthday[n];

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

{
cout << "Entering details for birthday " << (i + 1) << ":\n";

birthdays[i].inputBirthday();

cout << "\nDisplaying birthdays:\n";

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

birthdays[i].displayBirthday();

delete[] birthdays;

return 0;

}
If array of objects is declared as given belowwhich is the limitation on
objects?

Class_name arrayName[size];

 Static Size: The size of the array must be a constant expression or a


value known at compile time. This means you can't use a variable to
specify the size unless you're using dynamic allocation (e.g., with new).
 Memory Allocation: The entire array is allocated on the stack (if it's a
local array) or on the heap (if dynamically allocated). Large arrays can
lead to stack overflow if declared locally.
 Default Constructor Requirement: If the class has no default
constructor, or if the default constructor is not accessible, you cannot
create an array of that class. The compiler requires a way to construct
each object in the array.

#include<iostream>

using namespace std;

class Employee

int id;

char name[30];

public:

void getdata();

void putdata();

};

void Employee::getdata()

cout << "Enter Id : ";

cin >> id;

cout << "Enter Name : ";

cin >> name;

void Employee::putdata()

cout << id << " ";

cout << name << " ";

cout << endl;

int main()

{
Employee emp[30];

int n, i

cout << "Enter Number of Employees - ";

cin >> n;

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

emp[i].getdata();

cout << "Employee Data

Write a C++ program to declare class ‘Account’ having data members as


Account_No and

Balance. Accept this data for 10 accounts and display data of Accounts
having balance greater
than 10000.

#include <iostream>

using namespace std;

class Account

private:

int Account_No;

float Balance;

public:

void getData();

void display()

float getBalance()

};

void Account::getData()

cout << "Enter Account Number: ";

cin >> Account_No;

cout << "Enter Balance: ";

cin >> Balance;

void Account::display()

cout << "Account Number: " << Account_No << ", Balance: " << Balance
<< endl;

float Account::getBalance()
{

return Balance;

int main()

Account accounts[10];

for (int i = 0; i < 10; i++)

cout << "Enter details for Account " << (i + 1) << ":\n";

accounts[i].getData();

cout << "\nAccounts with Balance greater than 10,000:\n";

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

if (accounts[i].getBalance() > 10000) {

accounts[i].display();

return 0;

}
Experiment No: 10

Title of Write programs for –


Experiment
• Default Constructor

• Parameterized Constructor

• Copy Constructor

• Multiple Constructor in one class

Pratcical Related Questions:-


1. WAP to declare a class calculation. Display addition, subtraction,
multiplication, division of

two numbers. Use friend function.

#include <iostream>

using namespace std;

class Calculation

private:

float num1, num2;

public:

Calculation(float a, float b) : num1(a), num2(b) {}

friend void Calculations(Calculation calc);

};

void Calculations(Calculation calc)

cout << "Addition: " << (calc.num1 + calc.num2) << endl;

cout << "Subtraction: " << (calc.num1 - calc.num2) << endl;

cout << "Multiplication: " << (calc.num1 * calc.num2) << endl;

if (calc.num2 != 0)

{
cout << "Division: " << (calc.num1 / calc.num2) << endl;

else

cout << "Division: Cannot divide by zero!" << endl;

int main()

float a, b;

cout << "Enter two numbers: ";

cin >> a >> b;

Calculation calc(a, b);

Calculations(calc);

return 0;

}
a) How many member functions are

there in this C++ class excluding

constructors and destructors?

class Box

int capacity;

public:

void print();

friend void show();

bool compare();

friend bool lost();

};

ANS:-

 void print(); - A public member function.


 bool compare(); - Another public member function.
friend void show(); - A friend function, but not a member function of

the class.
 friend bool lost(); - Another friend function, but not a member function
of the class.
b) What will be the output of the

following C++ code?

#include <iostream>

#include <string>

using namespace std;

class Box

int capacity;

public:

Box(int cap){

capacity = cap;

friend void show();

};

void show()

Box b(10);

cout<<"Value of capacity

is: "<<b.capacity<<endl;

int main(int argc, char const *argv[])

show();
return 0;

Exercise:-
1. Write a C++ program to exchange the values of two variables using friend
function.

#include <iostream>

using namespace std;

class Exchange

private:

int a, b;

public:

Exchange(int x, int y) : a(x), b(y) {}

friend void swapValues(Exchange &e);

void display() const

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

};

void swapValues(Exchange &e)


{

int temp = e.a;

e.a = e.b;

e.b=temp;

int main()a

int x, y;

cout << "Enter two integers: ";

cin >> x >> y;

Exchange e(x, y);

cout << "Before swapping: ";

e.display();

swapValues(e);

cout << "After swapping: ";

e.display();

return 0;

}
2. WAP to create two classes test1 and test2 which stores marks of a
student. Read value for

class objects and calculate average of two tests using friend function.

#include <iostream>

using namespace std;

class Test1;

class Test2;

float calculateAverage(Test1, Test2);

class Test1

private:

float marks1;

public:

void readMarks()

cout << "Enter marks for Test 1: ";


cin >> marks1;

friend float calculateAverage(Test1 t1, Test2 t2);

};

class Test2

private:

float marks2;

public:

void readMarks()

cout << "Enter marks for Test 2: ";

cin >> marks2;

friend float calculateAverage(Test1 t1, Test2 t2);

};

float calculateAverage(Test1 t1, Test2 t2) {

return (t1.marks1 + t2.marks2) / 2;

int main() {

Test1 t1;

Test2 t2;

t1.readMarks();

t2.readMarks();

float average = calculateAverage(t1, t2);

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


return 0;

Experiment No: 11

Title of Write programs for –


Experiment
• Single level Inheritance

• Multilevel Inheritance

Practical Related Questions:-


1. Write a C++ program to define a class "Student" having data members
roll_no,

name. Derive a class "Marks" from "Student" having data members


ml,m2,m3,

total and percentage. Accept and display data for one student.

#include <iostream>

#include <string>

using namespace std;


class Student

protected:

int roll_no;

string name;

public:

void acceptData()

cout << "Enter Roll No: ";

cin >> roll_no;

cout << "Enter Name: ";

cin >> name;

void displayData()

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

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

};

class Marks : public Student

private:

float m1, m2, m3;

float total;

float percentage;
public:

void acceptMarks()

cout << "Enter Marks for 3 subjects:\n";

cout << "Marks 1: ";

cin >> m1;

cout << "Marks 2: ";

cin >> m2;

cout << "Marks 3: ";

cin >> m3;

calculateTotalAndPercentage();

void Total()

total = m1 + m2 + m3;

percentage = (total / 300) * 100;

void Marks()

displayData();

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

cout << "Percentage: " << percentage << "%" << endl;

};

int main()

{
Marks student;

student.acceptData();

student.acceptMarks();

cout << "\nStudent Data:\n";

student.displayMarks();

return 0;

2. Write a C++ program to implement following Multilevel Inheritance.


#include <iostream>

#include <string>

using namespace std;

class Person

protected:

string name;

string gender;

int age;

public:

void acceptPersonData()

cout << "Enter Name: ";


getline(cin, name);

cout << "Enter Gender: ";

getline(cin, gender);

cout << "Enter Age: ";

cin >> age;

cin.ignore();

void displayPersonData() const

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

cout << "Gender: " << gender << endl;

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

};

class Employee : public Person

protected:

int employeeID;

double salary;

public:

void acceptEmployeeData()

acceptPersonData();

cout << "Enter Employee ID: ";

cin >> employeeID;

cout << "Enter Salary: ";

cin >> salary;

cin.ignore();
void displayEmployeeData() const {

displayPersonData();

cout << "Employee ID: " << employeeID << endl;

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

};

class Programmer : public Employee

private:

int languagesKnown;

public:

void acceptProgrammerData()

acceptEmployeeData();

cout << "Enter Number of Languages Known: ";

cin >> languagesKnown;

cin.ignore();

void displayProgrammerData() const

displayEmployeeData();

cout << "Languages Known: " << languagesKnown << endl;

};

int main()

{
Programmer prog;

prog.acceptProgrammerData();

cout << "\nProgrammer Data:\n";

prog.displayProgrammerData();

return 0;

a) #include<iostream.h>

class Base
public:

Base(){}

~Base(){}

protected:

private:

};

class Derived:public Base

public:

Derived(){}

Derived(){}

private:

protected:

};

void main()

cout << "The program exceuted" <<

endl;

}
b) #include <iostream.h>

class A

public:

void print() {

cout <<

"print() in A";

};

class B :

private A

public:

void print() {

cout <<

"print() in B";

}
};

class C :

public B

public:

void print() {

cout <<

"print() in C";

A::print();}

};

void main()

Cb; b.print();

Exercise:-
1. WAP to implement inheritance shown below figure. Assume suitable
member function.

#include <iostream>

#include <string>

using namespace std;

class Furniture

protected:

string material;

double price;

public:

void acceptFurnitureData()

cout << "Enter Material: ";

getline(cin, material);

cout << "Enter Price: ";

cin >> price;

void displayFurnitureData()
{

cout << "Material: " << material << endl;

cout << "Price: $" << price << endl;

};

class Table : public Furniture

private:

double height;

double surfaceArea;

public:

void acceptTableData()

acceptFurnitureData();

cout << "Enter Height: ";

cin >> height;

cout << "Enter Surface Area: ";

cin >> surfaceArea;

void displayTableData() const

displayFurnitureData();

cout << "Height: " << height << " units" << endl;

cout << "Surface Area: " << surfaceArea << " sq. units" << endl;

};
int main()

Table myTable;

myTable.acceptTableData();

cout << "\nTable Data:\n";

myTable.displayTableData();

return 0;

}
2. Write a C++ program to define a class "Employee" having data members
emp_no,

emp_name and emp_designation. Derive a class "Salary" from "Employee"


having data

members basic, hra, da, gross_sal. Accept and display data for one
employee.

#include <iostream>

#include <string>

using namespace std;

class Employee

protected:

int emp_no;

string emp_name;

string emp_designation;

public:

void acceptEmployeeData()

cout << "Enter Employee Number: ";

cin >> emp_no;

cin.ignore();

cout << "Enter Employee Name: ";

getline(cin, emp_name);

cout << "Enter Employee Designation: ";

getline(cin, emp_designation);

}
void displayEmployeeData()

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

cout << "Employee Name: " << emp_name << endl;

cout << "Employee Designation: " << emp_designation << endl;

};

class Salary : public Employee

private:

double basic;

double hra;

double da;

double gross_sal;

public:

void acceptSalaryData()

acceptEmployeeData();

cout << "Enter Basic Salary: ";

cin >> basic;

cout << "Enter HRA: ";

cin >> hra;

cout << "Enter DA: ";

cin >> da;

gross_sal = basic + hra + da;

}
void displaySalaryData()

displayEmployeeData();

cout << "Basic Salary: $" << basic << endl;

cout << "HRA: $" << hra << endl;

cout << "DA: $" << da << endl;

cout << "Gross Salary: $" << gross_sal << endl;

};

int main()

Salary emp;

emp.acceptSalaryData();

cout << "\nEmployee Data:\n";

emp.displaySalaryData();

return 0;

}
Experiment No: 12

Title of Write programs to implement Multiple Inheritance


Experiment

Practical Related Questions:-

Write a C++ program to calculate the area and perimeter of rectangles

using concept of inheritance.

#include <iostream>

using namespace std;

class Area

public:

double calculateArea(double length, double breadth)

{
return length * breadth;

};

class Perimeter

public:

double calculatePerimeter(double length, double breadth) {

return 2 * (length + breadth);

};

class Rectangle : public Area, public Perimeter

private:

double length;

double breadth;

public

void getData()

cout << "Enter Length: ";

cin >> length;

cout << "Enter Breadth: ";

cin >> breadth;

void showData()

cout << "Length: " << length << endl;


cout << "Breadth: " << breadth << endl;

cout << "Area: " << calculateArea(length, breadth) << endl;

cout << "Perimeter: " << calculatePerimeter(length, breadth) << endl;

};

int main()

Rectangle rect;

cout << "\nRectangle Data:\n";

rect.showData();

return 0;

}
2. Complete the following questions
Exercise:-
Identify the following type of Inheritance shown . Write a definition of each
class .Write suitablemember functions to accept and display data for each
class.

#include <iostream>

#include <string>
class Employee

protected:

int emp_id;

string emp_name;

public:

void acceptData()

cout << "Enter Employee ID: ";

cin >> emp_id;

cout << "Enter Employee Name: ";

cin >>emp_name;

void displayData()

cout << "Employee ID: " << emp_id << std::endl;

cout << "Employee Name: " << emp_name << std::endl;

};

class EmpUnion : public Employee

protected:

int member_id;

public:

void acceptData()

Employee::acceptData();
cout << "Enter Union Member ID: ";

cin >> member_id;

void displayData()

Employee::displayData();

cout << "Union Member ID: " << member_id << std::endl;

};

class EmpInfo : public EmpUnion

private:

double basic_salary;

public:

void acceptData()

EmpUnion::acceptData();

cout << "Enter Basic Salary: ";

cin >> basic_salary;

void displayData()

EmpUnion::displayData();

cout << "Basic Salary: " << basic_salary << std::endl;

};
int main()

EmpInfo empInfo;

empInfo.acceptData();

empInfo.displayData();

return 0;

2. Write a Program to get the average marks of six subjects using the
Multiple Inheritance

#include <iostream>

using namespace std;

class Subject1

{
protected:

float subject1_marks;

float subject2_marks;

float subject3_marks;

public:

void acceptSubject1Marks()

cout << "Enter marks for Subject 1: ";

cin >> subject1_marks;

cout << "Enter marks for Subject 2: ";

cin >> subject2_marks;

cout << "Enter marks for Subject 3: ";

cin >> subject3_marks;

};

class Subject2

protected:

float subject4_marks;

float subject5_marks;

float subject6_marks;

public:

void acceptSubject2Marks()

cout << "Enter marks for Subject 4: ";

cin >> subject4_marks;

cout << "Enter marks for Subject 5: ";


cin >> subject5_marks;

cout << "Enter marks for Subject 6: ";

cin >> subject6_marks;

};

class Student : public Subject1, public Subject2

public:

void calculateAverage()

float total_marks = subject1_marks + subject2_marks + subject3_marks


+

subject4_marks + subject5_marks + subject6_marks;

float average = total_marks / 6;

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

};

int main()

Student student;

student.acceptSubject1Marks();

student.acceptSubject2Marks();

student.calculateAverage();

return 0;

}
Experiment No: 13

Title of Write programs to implement Hierarchical Inheritance


Experiment

Practical Related Questions:-

Write a C++ program to implement given class hierarchy.


#include <iostream>

#include <string>

class Player {

protected:

std::string name;

int matches;

public:

Player(const std::string& playerName, int playerMatches)

: name(playerName), matches(playerMatches) {}

virtual void display()

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

std::cout << "Matches Played: " << matches << std::endl;

};

class Batsman : public Player {

private:

int total_score;

float per_match_score;

public:

// Constructor to initialize batsman data

Batsman(const std::string& playerName, int playerMatches, int score)

: Player(playerName, playerMatches), total_score(score) {

per_match_score = static_cast<float>(total_score) / matches;


}

// Function to calculate average score

void calculateAverage() {

if (matches > 0) {

per_match_score = static_cast<float>(total_score) / matches;

} else {

per_match_score = 0;

// Overriding display function

void display() override {

Player::display(); // Call base class display

std::cout << "Total Score: " << total_score << std::endl;

std::cout << "Average Score per Match: " << per_match_score <<
std::endl;

};

class Bowler : public Player {

public:

// Constructor to initialize bowler data

Bowler(const std::string& playerName, int playerMatches)

: Player(playerName, playerMatches) {}

// Overriding display function


void display() override {

Player::display(); // Call base class display

std::cout << "Bowler: " << name << " is ready to bowl!" << std::endl;

};

int main() {

Batsman batsman("Sachin Tendulkar", 463, 18426); // Sample data

batsman.calculateAverage(); // Calculate average

batsman.display(); // Display batsman details

std::cout << std::endl;

Bowler bowler("Wasim Akram", 356); // Sample data

bowler.display(); // Display bowler details

return 0;

}
2.Write a C++ program to implement given figure class hierarchy.

a) #include <iostream>
using namespace std;

class Animal {

public:

void info() {

cout << "I am an animal." <<

endl;

};

class Dog : public Animal {

public:

void bark() {

cout << "I am a Dog. Woof

woof." << endl;

};

class Cat : public Animal {

public:

void meow() {

cout << "I am a Cat. Meow." <<

endl;

};

int main() {

class

Dog dog1;

cout << "Dog Class:" << endl;

dog1.info(); // parent Class function


dog1.bark();

class

Cat cat1;

cout << "\nCat Class:" << endl;

cat1.info(); // parent Class function

cat1.meow();

return 0;

b)#include<iostream.h>

#include<conio.h>

class emp

int id;

char name[20];
int sal;

public:

void accept()

cout<<"enter id, name and salary"<<endl;

cin>>id>>name>>sal;

void dis()

cout<<"id"<<id;

cout<<"name--"<<name<<endl;

cout<<"salary"<<sal; }

};

class manager : public emp

public:

acc1()

accept();

dis();

};

class clerk :public emp

public: acc2()

accept();
dis() ;

};

void main() {

manager m;

clerk c;

m.acc1();

c.acc2();

getch(); }

Exercise:-

Write a C++ program to implement the following inheritance. Accept and


display data for one programmer and one manager. Make display function
virtual.
#include <iostream>

#include <string>

using namespace std;

class Employee {

protected:

string name;

int id;

float salary;

public:

// Virtual display function

virtual void display() {

cout << "Employee ID: " << id << endl;

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

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

void accept()

{
cout << "Enter ID: ";

cin >> id;

cin.ignore(); // To ignore newline character after ID input

cout << "Enter Name: ";

getline(cin, name);

cout << "Enter Salary: ";

cin >> salary;

};

class Programmer : public Employee

public:

void display() override

cout << "Programmer Details:" << endl;

Employee::display(); // Call base class display

};

class Manager : public Employee

public:

void display() override

cout << "Manager Details:" << endl;

Employee::display(); // Call base class display


}

};

int main() {

Programmer programmer;

Manager manager;

cout << "Enter Programmer Details:" << endl;

programmer.accept();

cout << "\nEnter Manager Details:" << endl;

manager.accept();

cout << endl

programmer.display();

cout << endl;

manager.display();

return 0;

}
Experiment No: 14

Title of Write programs to implement Virtual Base Class.


Experiment

Practical Related Questions:-


1. Write a C++ program to implement the concept of virtual base
class for following figure.

#include <iostream>

#include <string>

using namespace std;

class Student

protected:

string name;

int rollNumber;

public:

Student(string n, int r) : name(n), rollNumber(r) {}

void displayStudentInfo() {

cout << "Name: " << name << ", Roll Number: " << rollNumber <<
endl;
}

};

class Test : virtual public Student

protected:

float marks1, marks2;

public:

Test(string n, int r, float m1, float m2)

: Student(n, r), marks1(m1), marks2(m2) {}

float totalMarks()

return marks1 + marks2;

};

class Sports : virtual public Student

protected:

float score;

public:

Sports(string n, int r, float s)

: Student(n, r), score(s) {}

float getScore()

return score;

};

class Result : public Test, public Sports


{

public:

Result(string n, int r, float m1, float m2, float s)

: Student(n, r), Test(n, r, m1, m2), Sports(n, r, s) {}

void displayResult()

displayStudentInfo();

cout << "Total Marks: " << totalMarks() << endl;

cout << "Sports Score: " << getScore() << endl;

cout << "Total Result: " << (totalMarks() + getScore()) << endl;

};

int main()

string name;

int rollNumber;

float marks1, marks2, sportsScore;

cout << "Enter student name: ";

cin >> name

cout << "Enter roll number: ";

cin >> rollNumber;

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

cin >> marks1;

cout << "Enter marks for subject 2: ";

cin >> marks2;

cout << "Enter sports score: ";


cin >> sportsScore;

Result student(name, rollNumber, marks1, marks2, sportsScore);

student.displayResult();

return 0;

2.Write a C++ program to implement given figure class hierarchy. Assume


suitable

member variables and member functions.


#include <iostream>
#include <string>
using namespace std;
class SavingAccount
{
protected:
string accountHolderName;
int accountNumber;
double balance;
public:
SavingAccount(string name, int number, double initialBalance)
: accountHolderName(name), accountNumber(number),
balance(initialBalance) {}
virtual void deposit(double amount)
{
balance += amount;
cout << "Deposited: " << amount << " | New Balance: " <<
balance << endl;
}
virtual void withdraw(double amount)
{
if (amount > balance)
{
cout << "Insufficient funds!" << endl;
}
else
{
balance -= amount;
cout << "Withdrew: " << amount << " | New Balance: "
<< balance << endl;
}
}
void displayAccountInfo()
{
cout << "Account Holder: " << accountHolderName <<
endl;
cout << "Account Number: " << accountNumber << endl;
cout << "Balance: " << balance << endl;
}
};
class CurrentAccount : public SavingAccount
{
private:
double overdraftLimit;
public:
CurrentAccount(string name, int number, double initialBalance,
double limit)
: SavingAccount(name, number, initialBalance),
overdraftLimit(limit) {}
void withdraw(double amount) override
{
if (amount > balance + overdraftLimit)
{
cout << "Withdrawal exceeds overdraft limit!" << endl;
}
else
{
balance -= amount;
cout << "Withdrew: " << amount << " | New Balance: "
<< balance << endl;
}
}
};
class FixedDeposit : public SavingAccount
{
private:
int tenure;
double interestRate;
public:
FixedDeposit(string name, int number, double initialBalance, int
t, double rate)
: SavingAccount(name, number, initialBalance), tenure(t),
interestRate(rate) {}
double calculateMaturityAmount()
{
return balance * (1 + (interestRate / 100) * tenure / 12);
}
void displayAccountInfo()
{
SavingAccount::displayAccountInfo();
cout << "Tenure: " << tenure << " months" << endl;
cout << "Interest Rate: " << interestRate << "%" << endl;
cout << "Maturity Amount: " << calculateMaturityAmount()
<< endl;
}
};
int main()
{
string name;
int accountNumber;
double initialBalance, overdraftLimit, interestRate;
int tenure
cout << "Enter Saving Account Holder Name: ";
getline(cin, name);
cout << "Enter Account Number: ";
cin >> accountNumber;
cout << "Enter Initial Balance: ";
cin >> initialBalance;
SavingAccount saving(name, accountNumber, initialBalance);
saving.displayAccountInfo();
cout << "\nEnter Current Account Holder Name: ";
cin.ignore();
getline(cin, name);
cout << "Enter Account Number: ";
cin >> accountNumber;
cout << "Enter Initial Balance: ";
cin >> initialBalance;
cout << "Enter Overdraft Limit: ";
cin >> overdraftLimit;
CurrentAccount current(name, accountNumber, initialBalance,
overdraftLimit);
current.displayAccountInfo();
cout << "\nEnter Fixed Deposit Account Holder Name: ";
cin.ignore();
getline(cin, name);
cout << "Enter Account Number: ";
cin >> accountNumber;
cout << "Enter Initial Balance: ";
cin >> initialBalance;
cout << "Enter Tenure (in months): ";
cin >> tenure;
cout << "Enter Interest Rate: ";
cin >> interestRate
FixedDeposit fixed(name, accountNumber, initialBalance,
tenure, interestRate);
fixed.displayAccountInfo();

return 0;
}
 Complete the following

A)#include <iostream.h>
struct a
{
int count;
};
Struct b
{
int* value;
};
struct c
public a,
public b
};
int main()
{
c* p new =c;
p->value=0;
cout<< "Inherited";
return 0;
}

b)#include<iostream.h>
class A
{
public:
void display()
{
cout<< “A\n”;
};
class B : public A
{
public:
void display()
{
cout<<”B\n”;
}
};
int main()
{
B b;
b.display();
b.A::display();
b.B::display();
return 0;
}

Exercise:-

1. Write a C++ program to implement the concept of Virtual Base


Class forfollowing figure.Assume suitable data and function
members.

#include <iostream>
#include <string>
using namespace std;
class Cricketer
{
protected:
string name;
int age;
int matchesPlayed;
public:
Cricketer(string n, int a, int m) : name(n), age(a), matchesPlayed(m)
{}
void displayCricketerInfo()
{
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Matches Played: " << matchesPlayed << endl;
}
};
class Bowler : virtual public Cricketer
{
protected:
int wicketsTaken;
double bowlingAverage;
public:
Bowler(string n, int a, int m, int w, double ba)
: Cricketer(n, a, m), wicketsTaken(w), bowlingAverage(ba) {}
void displayBowlerStats()
{
cout << "Wickets Taken: " << wicketsTaken << endl;
cout << "Bowling Average: " << bowlingAverage << endl;
}
};
class Batsman : virtual public Cricketer
{
protected:
int runsScored;
double battingAverage;
public:
Batsman(string n, int a, int m, int r, double ba)
: Cricketer(n, a, m), runsScored(r), battingAverage(ba) {}

void displayBatsmanStats() {
cout << "Runs Scored: " << runsScored << endl;
cout << "Batting Average: " << battingAverage << endl;
}
};
class AllRounder : public Bowler, public Batsman
{
public:
AllRounder(string n, int a, int m, int w, double baBowler, int r, double
baBatsman)
: Cricketer(n, a, m), Bowler(n, a, m, w, baBowler), Batsman(n, a,
m, r, baBatsman) {}
void displayAllRounderInfo()
{
displayCricketerInfo();
displayBowlerStats();
displayBatsmanStats();
}
};
int main()
{
string name;
int age, matchesPlayed, wicketsTaken, runsScored;
double bowlingAverage, battingAverage;
cout << "Enter Cricketer's Name: ";
getline(cin, name);
cout << "Enter Age: ";
cin >> age;
cout << "Enter Matches Played: ";
cin >> matchesPlayed;
cout << "Enter Wickets Taken: ";
cin >> wicketsTaken;
cout << "Enter Bowling Average: ";
cin >> bowlingAverage;
cout << "Enter Runs Scored: ";
cin >> runsScored;
cout << "Enter Batting Average: ";
cin >> battingAverage;
AllRounder player(name, age, matchesPlayed, wicketsTaken,
bowlingAverage, runsScored, battingAverage);
cout << "\nPlayer Information:\n";
player.displayAllRounderInfo();
return 0;
}

2.write a C++ program to implement the concept of Virtual Base Class


for following
figure.
Accept and Display information of one employee with his
name,code,basic
Pay,Experience and Gross Salary with the object of Employee class.
#include <iostream>

#include <string>

using namespace std;

class MasterData

protected:

string name;

int code;

public:

MasterData(string n, int c) : name(n), code(c) {}

void displayMasterData()

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


cout << "Code: " << code << endl;

};

class Account : virtual public MasterData

protected:

double basicSalary;

public:

Account(string n, int c, double salary)

MasterData(n, c), basicSalary(salary) {}

void displayAccountInfo()

cout << "Basic Salary: " << basicSalary << endl;

};

class Admin : virtual public MasterData

protected:

int experience;

public:

Admin(string n, int c, int exp)

MasterData(n, c), experience(exp) {}

void displayAdminInfo()

cout << "Experience: " << experience << " years" << endl;

};
class Employee : public Account, public Admin

private:

double grossSalary;

public:

Employee(string n, int c, double salary, int exp)

MasterData(n, c), Account(n, c, salary), Admin(n, c, exp)

calculateGrossSalary();

void calculateGrossSalary()

grossSalary = basicSalary + (0.20 * basicSalary);

void displayEmployeeInfo()

displayMasterData();

displayAccountInfo();

displayAdminInfo();

cout << "Gross Salary: " << grossSalary << endl;

};

int main()

string name;

int code, experience;


double basicSalary;

cout << "Enter Employee Name: ";

cin>>name

cout << "Enter Employee Code: ";

cin >> code;

cout << "Enter Basic Salary: ";

cin >> basicSalary;

cout << "Enter Experience (in years): ";

cin >> experience;

Employee emp(name, code, basicSalary, experience);

cout << "\nEmployee Information:\n";

emp.displayEmployeeInfo();

return 0;

}
Experiment No: 15

Title of Write programs which show use of constructors in derived


Experiment class.

Practical Related Questions:-

Write a program which show the use of constructor in derived


class.
#include <iostream>
#include <string>
using namespace std;
class Person
{
protected:
string name;
int age;

public:
Person(string n, int a) : name(n), age(a)
{
cout << "Person Constructor called" << endl;
}

void displayPersonIinfo()
{
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class Student : public Person
{
private:
string major;
double gpa;
public:
Student(string n, int a, string m, double g)
: Person(n, a), major(m), gpa(g)
{
cout << "Student Constructor called" << endl;
}
void displayStudentInfo()
{
displayPersonInfo();
cout << "Major: " << major << endl;
cout << "GPA: " << gpa << endl;
}
};
int main()
{
string name, major;
int age;
double gpa;
cout << "Enter Student Name: ";
getline(cin, name);
cout << "Enter Age: ";
cin >> age;
cout << "Enter Major: ";
cin >> major
cout << "Enter GPA: ";
cin >> gpa;
Student student(name, age, major, gpa);
cout << "\nStudent Information:\n";
student.displayStudentInfo();
return 0;
}

2.Complete the following :

a)class Base1
{

int data1;

public:

Base1(int i)

data1 = i;

cout<<"Base1 class constructor

called"<<endl;

void printDataBase1()

cout<<"The value of data1 is

"<<data1<<endl;

};

class Base2

int data2;

public:

Base2(int i)

data2 = i;

cout << "Base2 class constructor

called" << endl;

void printDataBase2(void){

cout << "The value of data2 is " <<


data2 << endl;

};

class Derived: public Base2, public Base1

int derived1, derived2;

public:

Derived(int a, int b, int c, int d) :

Base2(b), Base1

derived1 = c;

derived2 = d;

cout<< "Derived class constructor

called"<<endl;

void printDataDerived(void)

cout << "The value of derived1 is " <<

derived1 << endl;

cout << "The value of derived2 is " <<

derived2 << endl;

};

b) #include <iostream>

using namespace std;

class A
{

public:

A(int n )

cout << n;

};

class B: public A

public:

B(int n, double d)

: A(n)

cout << d;

};

class C: public B

public:

C(int n, double d, char ch)

:B(n, d)

cout <<ch;

};

int main()

{
C c(5, 4.3, 'R');

return 0;

Exercise:-

1. Write output of following code

#include <iostream>

using namespace std;

class Parent

public:

Parent()
{

cout << "Inside base class" << endl;

};

class Child : public Parent

public:

Child()

cout << "Inside sub class" << endl;

};

int main()

Child obj;

return 0;

2. #include <iostream>
using namespace std;

class Parent1

public:

Parent1()

cout << "Inside first base class" << endl;

};

class Parent2

public:

Parent2()

cout << "Inside second base class" << endl;

};

class Child : public Parent1, public Parent2

public:

Child()

cout << "Inside child class" << endl;

};

int main()

{
Child obj1;

return 0;

Experiment No: 16

Title of Write programs to implement-


Experiment

▪ Pointer to object

▪ 'this' pointer

Practical Related Questions:-

1 Write a C++ program to declare a class "Book" contammg data members


book_name, auther_name, and price . Accept this information for one object
of theclass using pointer to that object.

#include <iostream>

#include <string>
using namespace std;

class Book

private:

string book_name;

string author_name;

double price;

public:

void inputDetails()

cout << "Enter Book Name: ";

cin.ignore();

getline(cin, book_name);

cout << "Enter Author Name: ";

getline(cin, author_name);

cout << "Enter Price: ";

cin >> price;

void displayDetails() const

cout << "\nBook Name: " << book_name << endl;

cout << "Author Name: " << author_name << endl;

cout << "Price: $" << price << endl;

};

int main()

{
Book* bookPtr = new Book();

bookPtr->inputDetails();

bookPtr->displayDetails();

delete bookPtr;

return 0;

2 Write a C++ program to declare a class "Box" having data members


height,

width and breadth. Accept this information for one object using pointer to

that object . Display the area and volume of that object.


#include <iostream>

using namespace std;

class Box

private:

double height;

double width;

double breadth;

public:

void inputDetails()

cout << "Enter Height: ";

cin >> height;

cout << "Enter Width: ";

cin >> width;

cout << "Enter Breadth: ";

cin >> breadth;

void displayAreaAndVolume() const {

double area = width * breadth;

double volume = height * width * breadth;

cout << "Area: " << area << endl;

cout << "Volume: " << volume << endl;

}
};

int main() {

Box* boxPtr = new Box();

boxPtr->inputDetails();

boxPtr->displayAreaAndVolume();

delete boxPtr;

return 0;

3. Write a C++ program to declare a class birthday having data members


day, month,

year. Accept this information for five objects using pointer to the array of
objects

#include <iostream>

using namespace std;


class Birthday

private:

int day;

int month;

int year;

public:

void inputDetails()

cout << "Enter Day: ";

cin >> day;

cout << "Enter Month: ";

cin >> month;

cout << "Enter Year: ";

cin >> year;

void displayDetails()

cout << day << "/" << month << "/" << year << endl;

};

int main()

Birthday* birthdays = new Birthday[5];


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

cout << "Enter details for Birthday " << (i + 1) << ":\n";

birthdays[i].inputDetails();

cout << "\nEntered Birthdays:\n";

for (int i = 0; i < 5; ++i)

birthdays[i].displayDetails();

delete[] birthdays;

return 0;

}
Complete the following:

a) #include <iostream>

#include <iostream>

using namespace std;

class Employee

public:

int id;
string name;

float salary;

Employee(int id, string name, float salary)

this->id = id;

this->name = name;

this->salary = salary;

void display()

cout<<id<<" "<<name<<" "<<salary<<endl;

};

int main

Employee e1 =Employee(101, "Sonoo", 890000);

Employee e2=Employee(102, "Nakul", 59000); //creating

an object of Employee

e1.display();

e2.display();

return 0;

}
B) #include <iostream>

#include <string>

using namespace std;

class student

private:

int rollno;

string name;

public:

student():rollno(0),name(1111)

{}

student(int r, string n): rollno(r),name (n)

{}

void get()

cout<<"enter roll no"; cin>>rollno; cout<<"enter name";

cin>>name;

void print()

cout<<"roll no is 11<<rollno;

cout<<"name is "<<name;
};

void main ()

student *ps=new student; (*ps).get();

(*ps).print(); delete ps;

Exercise:-

#include <iostream.h>

#include<conio.h>

class myclass

int i;

public:

void read(int j)

i= j;

}
int getint()

return i;

};

void main()

clrscr();

rnyclass ob, *objectPointer;

objectPointer = &ob;

objectPointer->read(lO);

cout<<objectPointer->getint();

getch();

2. Which is the pointer which denotes the object calling the member
function?

a. Variable pointer b) This pointer

c) Null pointer d) Zero pointer

Ans:- b) This pointer


3. A pointer can be initialized with

a) Null b) zero

c)Address of an object of same type d) All of them

Ans:- All of them

4. Write a program which show the use of this pointer.

#include <iostream>

using namespace std;

class Rectangle

private:

double length;

double width;

public:

Rectangle(double length, double width)

this->length = length;

this->width = width;

double area()

return length * width;

}
void display()

cout << "Length: " << this->length << endl;

cout << "Width: " << this->width << endl;

};

int main()

Rectangle rect(10.5, 5.5);

rect.display();

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

return 0;

Experiment No: 17

Title of Write programs for-


Experiment
• Pointer to derived class in single inheritance

• Pointer to derived class in multilevel inheritance


Practical Related Questions:-

1. Write a C++ program declare a class "polygon" having data members


width

and height. Derive classes "rectangle" and "triangle" from "polygon" having

area() as a member function. Calculate area of triangle and rectangle using

pointer to derived class object.

#include <iostream>

using namespace std;

class Polygon

protected:

double width;

double height;

public:

Polygon(double w, double h) : width(w), height(h) {}

};

class Rectangle : public Polygon

public:

Rectangle(double w, double h) : Polygon(w, h) {}

double area()

{
return width * height;

};

class Triangle : public Polygon

public:

Triangle(double w, double h) : Polygon(w, h) {}

double area()

return 0.5 * width * height;

};

int main()

Polygon p;

Rectangle rect(10, 5);

Triangle tri(10, 5);

p = &rect;

cout << "Area of Rectangle: " << static_cast<Rectangle*>(p)->area() <<


endl;

p = &tri;

cout << "Area of Triangle: " << static_cast<Triangle*>(p)->area() <<


endl;
return 0;

Write a program which show the use of Pointer to derived class in multilevel

Inheritance.

#include <iostream>

using namespace std;

class Animal

public:

void sound()

cout << "Animal sound" << endl;

};

class Mammal : public Animal


{

public:

void walk()

cout << "Mammal walks" << endl;

};

class Dog : public Mammal

public:

void bark()

cout << "Dog barks" << endl;

};

int main() {

Dog* dogPtr = new Dog();

dogPtr->sound();

dogPtr->walk();

dogPtr->bark();

delete dogPtr;

return 0;

}
3.Complete the following:-

a) #include<iostream.h>

class base

public:

int nl;

void show()

cout<<"\nnl"<<nl;

};

class derive:public base

public:

int n2;

void show()

cout<<"\nnl "<<nl;
cout<<"\nn2 "<<n2;

};

int main()

base b;

base *bptr;

cout<<"Pointer of base class points to it";

bptr=&b;

bptr->n1=44;

bptr->show();

derived d;

cout<<"\n";

bptr=&d;

bptr->n1=66;

bptr->show();

return 0;

b) #include <iostream.h>
class BaseClass

int x;

public:

void setx(int i)

X = i;

int getx()

return x;

};

class DerivedClass : public BaseClass

int y;

public:

void sety(int i)

y = i;

int gety()

return y;

};

int main()

BaseClass *p;

BaseClass baseObject;

DerivedClass derivedObject;
p = &baseObject;

p->setx(l0);

cout << "Base object x: "<< p->getx() <<"\n" ;

p = &derivedObject;

p->setx(99);

derivedObject.sety(88);

cout << "Derived object x: " << p->getx () <<"\n" ;

cout << "Derived object y: "<< derivedObject.gety() << '\n';

return 0;

Exercise:-

1.State output of the following code:

#include<iostream.h>

class base

public:

void show()

cout << "base\n";

};
class derived: public base

public:

void show()

cout << "derived\n";

};

void main()

base bl;

bl.show();

derived dl;

dl.show();

base *pb = &bl;

pb->show();

pb = &dl;

pb->show();

}
2. A pointer to the base class can hold address of

A) only base class object B) only derived class object

C) base class object as well as derived class object D) None of the above

Ans:-

C) base class object as well as derived object

3. A pointer can be initialized with

a) Null b) zero

c)Address of an object of same type d) All of them

Ans:-

d) All of them

3.Which variable stores the memory address of another variable?

A) Reference B) Pointer

C) Array D) None of the above

Ans:-

B) Pointer

Experiment No: 18

Title of Write programs which show the use of function


Experiment overloading

Practical Related questions:-


1.Write a C++ Program to interchange the values of two int , float and

char using function overloading.

#include <iostream>
using namespace std;

void interchange(int &a, int &b)

int temp = a;

a = b;

b = temp;

void interchange(float &a, float &b)

float temp = a;

a = b;

b = temp;

void interchange(char &a, char &b)

char temp = a;

a = b;

b = temp;

int main()

int int1 = 5, int2 = 10;

cout << "Before interchanging: int1 = " << int1 << ", int2 = " << int2
<< endl;

interchange(int1, int2);

cout << "After interchanging: int1 = " << int1 << ", int2 = " <<int2 <<
endl;
float float1 = 5.5, float2 = 10.5;

cout << "Before interchanging: float1 = " << float1 << ", float2 = " <<
float2 << endl;

interchange(float1, float2);

cout << "After interchanging: float1 = " << float1 << ", float2 = " <<
float2 << endl;

char char1 = 'A', char2 = 'B';

cout << "Before interchanging: char1 = " << char1 << ", char2 = " <<
char2 << endl;

interchange(char1, char2);

cout << "After interchanging: char1 = " << char1 << ", char2 = " <<
char2 << endl;

return 0;

}
2.Write a C++ Program that find the sum of two int and double number

using function overloading.

#include <iostream>

using namespace std;

int sum(int a, int b)

return a + b;

double sum(double a, double b)

return a + b;

int main()

int int1 = 5, int2 = 10;

double double1 = 5.5, double2 = 10.5;

int intSum = sum(int1, int2);

double doubleSum = sum(double1, double2);

cout << intSum << endl;

cout << doubleSum << endl;

return 0;

}
3. Write C++ program to find the area of various geometrical shapes by

Function overloading. (eg.Area of circle, circumference of circle etc...)

#include <iostream>

using namespace std;

const double Pi = 3.14159;

double area(double radius)

return Pi * radius * radius;

double circumference(double radius)

return 2 * Pi * radius;

double area(double length, double width)


{

return length * width;

double area(double base, double height, bool isTriangle)

return 0.5 * base * height;

int main()

double radius = 5.0;

double length = 4.0, width = 6.0;

double base = 5.0, height = 3.0;

cout << "Area of Circle: " << area(radius)<< endl;

cout << "Circumference of Circle:"<<circumference(radius)<<endl;

cout << "Area of Rectangle: " << area(length, width)<< endl;

cout << "Area of Triangle: " << area(base, height, true)<< endl;

return 0;

}
4. Complete the following table:

a) #include<iostream.h>

int absolute(int);

float absolute(float);

int main()

int a= -5;

float b = 5.5;

cout << "Absolute value of"<< a<<" "<< absolute(a)

<< endl;

cout << "Absolute value of"<< b <<" "<< absolute(b);

return 0;

int absolute(int var)

if (var < 0)
{

var= -var;

return var;

float absolute(float var)

if (var< 0.0)

var= -var;

return var;

b) #include <iostream.h>

class Test

public:

int main(int s)
{

cout << s << "\n";

return 0;

int main(char *s)

cout << s << endl;

return 0;

int main(int s ,int m)

cout << s <<" "<< m;

return 0;

};

int main()

Test obj;

obj.main(3);

obj.main("! like C++");

obj.main(9, 6);

return 0;

}
Exercise:
1.Does constructor overloading isimplementation of function overloading?

#include <iostream>

using namespace std;

class Box

public:

Box()

cout << "Default constructor called" << endl;

Box(int length)

cout << "Constructor with one parameter called: " << length << endl;

Box(int length, int width)

{
cout << "Constructor with two parameters called: " << length << ", "
<< width << endl;

};

int main()

Box box1;

Box box2(5);

Box box3(5, 10);

return 0;

2.State output of the following code:

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

int operate (int a, int b)

return (a * b);

float operate (float a, float b)

return (a / b);

int main()

int X = 5, y = 2; float n = 5.0,

m = 2.0;

cout << operate(x, y) <<"\t"; cout

<< operate (n, m);

return 0;

}
3. Which of the following in Object Oriented Programming is supported
by Function
overloading and default arguments features of C++?
a) Inheritance b) Polymorphism
c) Encapsulation d) None of these
ANS:-
b) Polymorphism

4. Overloaded functions are


a) Very long functions that can hardly run
b) One function containing another one or more functions inside it.
c) Two or more functions with the same name but different number
parameters
or type.
d) None of these
ANS:-
c) Two or more functions with the same name but different number
parameters
or type.

Experiment No: 19

Title of Write programs to overload unary operator using-


Experiment
• Member function

• Friend function

You might also like