0% found this document useful (0 votes)
19 views122 pages

C++ Object-Oriented Programming Lab Guide

This document is a practical file for Object Oriented Programming using C++ at I.K Gujral Punjab Technical University. It includes a series of programming exercises that cover various concepts such as classes, functions, inheritance, operator overloading, and file handling. Each exercise is designed to demonstrate specific programming techniques and concepts in C++.
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)
19 views122 pages

C++ Object-Oriented Programming Lab Guide

This document is a practical file for Object Oriented Programming using C++ at I.K Gujral Punjab Technical University. It includes a series of programming exercises that cover various concepts such as classes, functions, inheritance, operator overloading, and file handling. Each exercise is designed to demonstrate specific programming techniques and concepts in C++.
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

PRACTICAL FILE

On
OBJECT ORIENTED
PROGRAMMING
USING C++ LABORATORY

I.K GUJRAL PUNJAB TECHNICAL UNIVERSITY, JALANDHAR


KAPURTHALA

BACHELOR OF COMPUTER APPLICATION

Submitted To: Submitted By:


Mr. Jagmeet Singh
Assistant Professor

Sr. No. Topic Page No.


1
Write a program to enter mark of 6 different subjects and find out the total
1.
mark (Using cin and cout statement)
Write a function using reference variables as arguments to swap the values of
2.
pair of integers
3. Write a function to find largest of three numbers
4. Write a program to find the factorial of a number
Define a class to represent a bank account which includes the following
members as
Data Members:
a) Name of the depositor
b) Account number
c) Withdrawal amount
5.
d) Balance amount in the account
Member Functions:
a) To assign initial values
b) To deposit an amount
c) To withdraw an amount after checking the balance
To display name and balance
Write the above Program for handling n number of account holders using
6
array of objects.
7 Write a Program to demonstrate Friend Function
8 Write a Program to demonstrate Inline Function
9 Write a Program to demonstrate Static Members & Functions
10 Write a Program to demonstrate Scope Resolution Operator
11 Write a Program to demonstrate Pass by Reference
12 Write a Program to demonstrate Pass by Value
Write a Program to demonstrate Constructors
a) Default Constructor
13 b) Parameterized Constructor
c) Copy Constructor
14 Write a Program to demonstrate Destructor
15 Write a Program to demonstrate setprecision() and endl
16 Write a Program to define the member function inside and outside the class
17 Write a Program to demonstrate Array of Objects
18 Write a Program to demonstrate Call by Value
19 Write a Program to demonstrate Call by Address
20 Write a Program to swap private data of two classes using Friend Function
21 Write a Program to demonstrate Function Overloading
22 Write a Program to demonstrate Constructor Overloading
23 Write a Program to demonstrate Inheritance
24 Write a Program to demonstrate Public Derivation/Inheritance
25 Write a Program to demonstrate Private Inheritance/Derivation
26 Write a Program to demonstrate Protected Data Members
27 Write a Program to demonstrate Protected Inheritance/Derivation
28 Write a Program to demonstrate Single Inheritance
29 Write a Program to demonstrate Multi-Level Inheritance
30 Write a Program to demonstrate Multiple Inheritance
2
31 Write a Program to Handle Multiple Inheritance Ambiguity
32 Write a Program to demonstrate Hierarchical Inheritance
Consider a publishing company that markets both book and audio cassette
version to its works. Create a class Publication that stores the title (a string)
and price (type float) of a publication. Derive the following two classes from
the above Publication class: Book which adds a page count (int) and Tape
33 which adds a playing time in minutes(float). Each class should have
getdata() function to get its data from the user at the keyboard. Write the
main() function to test the Book and Tape classes by creating instances
of them asking the user to fill in data with getdata() and then
displaying it using putdata().
34 Write a Program to demonstrate Hybrid Inheritance
Write a Program to Resolve Hybrid Inheritance Ambiguity Or Diamond
35
Problem using Virtual Base Class
Write a Program to compute Area of Right Angle Triangle, Equilateral
36
Triangle, Isosceles Triangle using function overloading
Consider an example of declaring the examination result. Design three
classes student, exam and result. The student has data members such as
37 rollno, name. Create the class exam by inheriting the student class. The exam
class adds data members representing the marks scored in 5 subjects. Derive
the result from exam-class and it has own data members like total, average.
Write a Program to demonstrate Unary Operator Overloading using Member
38
Function
Write a Program to demonstrate Unary Operator Overloading using Friend
39
Function
Write a Program to demonstrate Binary Operator Overloading using Member
40
Function
Write a Program to demonstrate Binary Operator Overloading using Friend
41
Function
Write a Program to Concatenate Two Strings Objects using Binary Operator
42
(+) Overloading
Write a Program of Operator Overloading when Friend function is
43
Compulsory
44 Write a Program to illustrate concept of Virtual Functions
45 Write a Program to demonstrate Runtime Polymorphism
46 Write a Program to demonstrate Manipulators
47 Write a Program to Create (Open and Close) a Empty File
48 Write a Program to Write data into a File
49 Write a Program to Read data from a File
50 Write a Program to Append data into a File
51 Write a Program to demonstrate Abstract Classes

1) Write a program to enter mark of 6 different subjects and find out the total marks.
3
/*Program to find sum total of six different subjects*/

using namespace std;


#include<iostream>
#include<iomanip>
class result
{
private:
int s1,s2,s3,s4,s5,s6,tot;
float per;
public:
void get_subjects_marks()
{
cout<<"\n Enter Marks of six subjects: ";
cin>>s1>>s2>>s3>>s4>>s5>>s6;
}
void calculate_per()
{
tot=s1+s2+s3+s4+s5+s6;
per=(tot/600.0f)*100;
//per=((float)tot/600)*100; //type casting
}
void display()
{
cout<<"\n Total Marks: "<<tot;
cout<<"\n Percentage: "<<setprecision(4)<<per;
//printf("\n Percentage=%.2f",per);
}
};

int main()
{
result s1; //object declaration
//[Link]=500;
s1.get_subjects_marks();
s1.calculate_per();
[Link]();
return 0;
}

4
5
2) Write a function using reference variables as arguments to swap the values of pair of
integers

/*Program to swap two numbers using reference variables*/

#include<iostream>

using namespace std;

void swap(int x, int y) // x and y are reference variables

int temp;

temp=x;

x=y;

y=temp;

int main()

int a=2, b=8;

cout<<"\n Before Swapping: ";

cout<<"\n\t A: "<<a<<"\t B: "<<b;

swap(a,b); //function call

cout<<"\n After Swapping: ";

cout<<"\n\t A: "<<b<<"\t B: "<<a;

return 0;

6
3) Write a function to find largest of three numbers

/*Program to find the largest number among three numbers*/

#include<iostream>

using namespace std;

//funtion to find the Largest among three numbers

int findLargest(int num1, int num2, int num3)

if(num1 >= num2 && num1 >= num3)

return num1;

else if(num2 >= num1 && num2 >= num3)

return num2;

else

return num3;

int main()

int num1, num2, num3;

//Input three numbers from the user

cout <<"\n Enter Three Numbers: ";

cin >> num1 >> num2 >> num3;

//call the function to find the largest number


7
int largest = findLargest( num1, num2, num3 );

//Display the result

cout << "\n The Largest Number: " << largest << endl;

return 0;

8
4) Write a program to find the factorial of a number using Class

/*Write a program to find the factorial of a number using class*/

#include<iostream>

using namespace std;

class Factorial {

private:

int num;

long fact;

public:

void inputNumber() {

cout<<"\n Enter any Positive Integer: ";

cin>>num;

void calculateFactorial() {

start:

if(num < 0) {

cout<<"\n Factorial of a Negative Number doesn't exist!!"<<endl;

cout<<"\n Please Input Positive Integer"<<endl;

inputNumber(); //Nested member-functions

goto start;

else if(num == 0) {

cout<<"\n Factorial of zero is 1."<<endl;

9
else {

int i;

fact = 1;

for(i=num;i>=1;i--) {

fact = fact * i;

cout<<"\n Factorial of "<<num<<" is "<<fact<<endl;

};

int main() {

Factorial obj;

[Link]();

[Link]();

return 0;

10
5) Define a class to represent a bank account which includes the following members as

Data Members:

a) Name of the depositor


b) Account number
c) Withdrawal amount
d) Balance amount in the account

Member Functions:

a) To assign initial values


b) To deposit an amount
c) To withdraw an amount after checking the balance
d) To display name and balance

/*Program for Banking Management System*/

#include<iostream>

using namespace std;

class Bank {

private:

string name;

long int contactNo;

double bal;

long int acc_no;

static long int count;

public:

void inputDetails(int amt=1000) //Default value is set to 1000

[Link]();

cout<<"\n Enter name of the account holder: ";


11
getline(cin,name);

cout<<"\n Enter contact number: ";

cin>>contactNo;

bal = amt;

count++;

acc_no=count;

cout<<"\n Deposit minimum balance of atleast 1000!!";

void diposit(int amt)

bal = bal + amt;

void withdrawal(int amt)

if((bal-amt)>=1000) //amt=500 bal=1500-500=1000

bal=bal-amt;

cout<<"\n Balance after withdrawal operation: "<<bal;

else {

cout<<"\n Insufficient funds in your account";

void display()

12
{

cout<<"\n Account Holder Information: ";

cout<<"\n\t Account Number: "<<acc_no;

cout<<"\n\t Name: "<<name;

cout<<"\n\t Contact No. "<<contactNo;

cout<<"\n\t Balance: "<<bal;

};

long Bank::count=2019900;

int main()

int amt;

Bank b1;

cout<<" Enter Initial amount for opening account: ";

cin>>amt;

if(amt<1000) {

[Link]();

else {

[Link](amt);

int op;

cout<<endl;

system("pause");

13
do

system("CLS");

cout<<"1. Deposit"<<endl;

cout<<"2. Withdraw"<<endl;

cout<<"3. Display Basic Information"<<endl;

cout<<"4. Exit"<<endl;

cout<<" Enter option: "<<endl;

cin>>op;

switch(op)

case 1:

cout<<"\n Enter amount, you want to deposit: "<<endl;

cin>>amt;

[Link](amt);

break;

case 2:

cout<<"\n Enter amount you want to withdraw: "<<endl;

cin>>amt;

[Link](amt);

break;

case 3:

[Link]();

break;

14
case 4:

exit(1);

default:

cout<<"\n Enter option between 1 to 4";

cout<<endl;

system("pause");

} while(1); //infinte loop

15
16
6) Write the above Program for handling n number of account holders using array of
objects.

/*program to Demonstrate Banking Management System*/

#include <iostream>

#include <string>

using namespace std;

class BankAccount {

private:

string depositorName;

int accountNumber;

double balance;

public:

BankAccount(string name = "", int accNo = 0, double bal = 0.0) { // Constructor to initialize values

depositorName = name;

accountNumber = accNo;

balance = bal;

void deposit(double amount) { // Function to deposit an amount

if (amount > 0) {

balance += amount;

cout << "\n Amount deposited successfully!" << endl;

} else {

17
cout << "\n Invalid deposit amount!" << endl;

void withdraw(double amount) { // Function to withdraw an amount

if (amount > 0 && amount <= balance) {

balance -= amount;

cout << "\n Withdrawal successful!" << endl;

} else {

cout << "\n Insufficient balance or invalid amount!" << endl;

void display() const { // Function to display account details

cout << "\n Depositor Name: " << depositorName << endl;

cout << "\n Account Number: " << accountNumber << endl;

cout << "\n Balance: $" << balance << endl;

};

int main() {

int n;

cout << "\n Enter the number of account holders: ";

cin >> n;

BankAccount accounts[n];

18
// Input details for each account holder

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

string name;

int accNo;

double balance;

cout << "\n Enter details for Account " << i + 1 << endl;

cout << "\n Enter Name: ";

[Link]();

getline(cin, name);

cout << "\n Enter Account Number: ";

cin >> accNo;

cout << "\n Enter Initial Balance: ";

cin >> balance;

accounts[i] = BankAccount(name, accNo, balance);

// Performing operations

int choice, accIndex;

double amount;

do {

cout << "\nBank Account Management System\n";

cout << "1. Deposit Money\n";

19
cout << "2. Withdraw Money\n";

cout << "3. Display Account Details\n";

cout << "4. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

switch (choice) {

case 1:

cout << "Enter account index (1 to " << n << "): ";

cin >> accIndex;

if (accIndex > 0 && accIndex <= n) {

cout << "Enter amount to deposit: ";

cin >> amount;

accounts[accIndex - 1].deposit(amount);

} else {

cout << "Invalid account index!" << endl;

break;

case 2:

cout << "Enter account index (1 to " << n << "): ";

cin >> accIndex;

if (accIndex > 0 && accIndex <= n) {

cout << "Enter amount to withdraw: ";

cin >> amount;

20
accounts[accIndex - 1].withdraw(amount);

} else {

cout << "Invalid account index!" << endl;

break;

case 3:

cout << "Enter account index (1 to " << n << "): ";

cin >> accIndex;

if (accIndex > 0 && accIndex <= n) {

accounts[accIndex - 1].display();

} else {

cout << "Invalid account index!" << endl;

break;

case 4:

cout << "Exiting the program..." << endl;

break;

default:

cout << "Invalid choice! Please try again." << endl;

} while (choice != 4);

return 0;

21
22
7) Write a Program to Demonstrate Friend Function

/*Program to demonstrate Friend Function*/

#include<iostream>

using namespace std;

class Demo {

int n1,n2;

public:

Demo(int x, int y) {

n1=x;

n2=y;

friend void Average(Demo); //Friend function declaration

};

void Average(Demo obj) {

double avg;

avg=((double)obj.n1+obj.n2)/2;

cout<<"\n Average of Private Data Members: "<<avg;

int main() {

Demo d1(7,4);

Average(d1); //Friend function call

return 0;

23
24
8) Write a Program to demonstrate Inline Function

/*Program to demonstrate Inline Function*/

#include <iostream>

using namespace std;

inline int Max(int x, int y)

return (x > y)? x : y; //? :

// Main function for the program

int main()

int a,b;

cout << "\n Max (4,8): " << Max(4,8) << endl;

cout << "\n Max (6,9): " << Max(6,9) << endl;

cout<<"\n Enter value of a and b: ";

cin>>a>>b;

cout << "\n Max ("<<a<<","<<b<<"): "<< Max(a,b) << endl;

return 0;

25
9) Write a Program to demonstrate Static Members & Functions

/*Program to demonstrate static data members and static member function*/

#include <iostream>

using namespace std;

class Student {

string name, add;

int age, rollNo;

static int count,sem;

public:

Student() {

cout<<"\n Enter name and age of student: ";

cin>>name>>age;

cout<<"\n Enter address: ";

[Link]();

getline(cin,add);

count++;

rollNo=count;

void display() {

cout<<"\n\t Roll Number: "<<rollNo;

cout<<"\n\t Name: "<<name;

cout<<"\n\t Age: "<<age;

cout<<"\n\t Class: BCA"<<sem;

cout<<"\n\t Address: "<<add<<endl;


26
}

static void UpdateSemester(); //static member function

};

int Student::count=2450;

int Student::sem=1;

void Student::UpdateSemester() {

sem+=1;

int main(){

Student s1; //default constructor will be invoked

cout<<"\n 1st Student's Record";

[Link]();

Student s2;

cout<<"\n 2nd Student's Record";

[Link]();

Student::UpdateSemester(); //call to static member function

cout<<"\n After Final Exams!!\n";

cout<<"\n 1st Student's Record";

[Link]();

cout<<"\n 2nd Student's Record";

[Link]();

return 0;

27
28
10)Write a Program to demonstrate Scope Resolution Operator

/*Program to demonstrate same name local and global variables using Scope Resolution Operator*/

#include <iostream>

using namespace std;

int a=6; //global variable declaration

int fun1();

void fun2(int);

int main() {

int a=7;

cout<<"\n A= "<<a;

cout<<"\n A= "<<::a;

int t=fun1(); //function-1 call

cout<<"\n Returned value: "<<t;

fun2(t); //function-2 call

cout<<"\n A= "<<a;

int fun1() {

a=a+5;

cout<<"\n A= "<<a;

a=a-7;

return(a);

void fun2(int a) {

cout<<"\n A= "<<a;

29
a=a*5;

cout<<"\n A= "<<a;

cout<<"\n A= "<<::a;

30
11) Write a Program to demonstrate Pass by Reference

/*Program to demonstrate Pass by Reference*/

#include <iostream>

using namespace std;

void swap(int&, int&); //function prototype (reference variables)

int main() {

int a,b;

cout<<"\n Enter Value of A and B: ";

cin>>a>>b;

cout<<"\n Before Swapping: ";

cout<<"\n\t A= "<<a;

cout<<"\n\t B= "<<b;

swap(a,b); //Pass by actual arguments

cout<<"\n Values of A and B in main (after swapping)";

cout<<"\n\t A= "<<a;

cout<<"\n\t B= "<<b;

return 0;

void swap(int &x, int &y) //x,y will become alias of a,b

int temp;

temp=x; //temp=10

x=y; //x=20 i.e. a=20

y=temp; //y=10 i.e. b=10


31
}

32
12) Write a Program to demonstrate Pass by Value

/*Program to show how pass by value works by swapping two given numbers*/

#include <iostream>

using namespace std;

void swap(int, int); //function prototype

int main() {

int a=4, b=2;

cout<<"\n Before calling (in main): ";

cout<<" A= "<<a<<" B= "<<b<<endl;

swap(a,b); //call by value

cout<<"\n After calling (in main): ";

cout<<" A= "<<a<<" B= "<<b<<endl;

return 0;

void swap(int x, int y) {

int temp;

temp=x;

x=y;

y=temp;

cout<<"\n After Modification (in function): ";

cout<<"X= "<<x<<" Y= "<<y<<endl;

33
34
13)Write a Program to demonstrate Constructors
a) Default Constructor
b) Parameterized Constructor
c) Copy Constructor

/*Program to demonstrate Default constructor*/

#include <iostream>

using namespace std;

class MyClass {

private:

int num;

public:

MyClass() { //Default constructor

num=12; //Initialize num with a default value

cout<<"\n Default constructor called!"<<endl;

void display() { //function to display the value of num

cout<<"\n Value of num: "<<num<<endl;

};

int main() {

MyClass obj; //Creating an object of MyClass using default constructor

[Link](); //call the display function to show the value of num

return 0;

35
36
/*Program to demonstrate Parameterized Constructor*/

#include <iostream>

using namespace std;

class Rectangle {

int l,b;

public:

Rectangle(int x, int y) { //parameterized constructor

cout<<"\n Parameterized Constructor Invoked";

l=x;

b=y;

void display() {

cout<<"\n\t Area of Rectangle: "<<l*b;

};

int main() {

Rectangle r1(2,8); //parameterized constructor will be invoked

cout<<"\n 1st Rectangle";

[Link]();

cout<<"\n------------------------------------------------------";

Rectangle r2(7,4); //parameterized constructor will be invoked

cout<<"\n 2nd Rectangle";

[Link]();

return 0;

37
}

38
/*Program to demonstrate Copy constructor*/

#include <iostream>

using namespace std;

class sample {

int a;

public:

sample() { //default or zero parameter constructor

cout<<"\n Default Contructor Invoked";

a=7;

sample(int x) { //parameterized constructor

cout<<"\n Parameterized Constructor Invoked";

a=x;

sample(sample &obj) { //copy constructor

cout<<"\n Copy Constructor Invoked";

a=obj.a;

void display() {

cout<<"\n\t A: "<<a;

};

int main() {

sample s1; //default constructor will be invoked

39
cout<<"\n S1 Object's Value";

[Link]();

sample s2; //parameterized constructor will be invoked

cout<<"\n S2 Object's Value";

[Link]();

sample s3=s1; //s3(s1);copy contructor will be invoked

cout<<"\n S3 Object's Value (Copy from S1)";

[Link]();

sample s4(s2); //same as sample s4(s2);

cout<<"\n S4 Object's Value (Copy from S2)";

[Link]();

return 0;

40
14)Write a Program to demonstrate Destructor

/*Program to demonstrate Destructor*/

#include <iostream>

using namespace std;

int count=10;

class Alpha {

public:

Alpha() { //default constructor

count++;

cout<<" \n "<<count<<" Object Created";

~Alpha() { //destructor function

cout<<" \n "<<count<<" Object Destroyed";

count--;

};

int main() {

cout<<"\n Enter main";

Alpha a1,a2; //objects declaration

{ //opening curly brace start of block

cout<<"\n\n Enter Block1";

Alpha a3;

cout<<"\n Block=1 Ends";

} //End of block, Destructor will be invoked


41
cout<<"\n\n Re-Enter main";

return 0;

} //End of main, Destructor will be invoked

42
15)Write a Program to demonstrate setprecision() and endl

/*Program to demonstrate setprecision() and endl man*/

using namespace std;

#include <iostream>

#include <iomanip>

int main() {

float a,b; //variable declaration

cout<<"\n Enter Two Integers: "<<endl;

cin>>a>>b;

float div;

div=a/b;

cout<<" Division Result: "<<setprecision(3)<<div<<endl;

return 0;

43
16)Write a Program to define the member function inside and outside the class

/*Program to define the member function inside and outside the class*/

#include <iostream>

using namespace std;

class Student {

char name[30];

int age;

float per;

public: //member function definition inside the class

void getdata() {

cout<<"\n Enter the Name of the Student: ";

[Link](name,30);

cout<<"\n Enter the Age of the Student: ";

cin>>age;

cout<<"\n Enter the Percentage of the Student: ";

cin>>per;

void display(); //member function declaration

};

class Employee {

string name;

int age;

string des;

public:
44
void getdata() {

[Link]();

cout<<"\n Enter the Name of the Employee: ";

getline(cin,name);

cout<<"\n Enter the Age of the Employee: ";

cin>>age;

[Link]();

cout<<"\n Enter Designation of Employee: ";

getline(cin,des);

void display(); //member function declaration

};

void Student::display() { //member function definition outside the class

cout<<"\n\t Name: "<<name;

cout<<"\n\t Age: "<<age;

cout<<"\n\t Percentage: "<<per;

void Employee::display() { //member function definition

cout<<"\n\t Name: "<<name;

cout<<"\n\t Age: "<<age;

cout<<"\n\t Designation: "<<des;

int main() {

Student s1;

45
cout<<"\n Enter Student Information\n";

[Link]();

cout<<"\n Student's Record ";

[Link]();

Employee e1;

cout<<"\n\n Enter Employee Information\n";

[Link]();

cout<<"\n Employee's Record ";

[Link]();

return 0;

46
17)Write a Program to demonstrate Array of Objects

/*Program to demonstrate Array of Objects*/

#include <iostream>

using namespace std;

class Student {

string name;

int marks;

public:

void getDetail() {

cout<<"\n Enter Name: ";

getline(cin,name);

cout<<" Enter Marks: ";

cin>>marks;

[Link]();

void displayInfo() {

cout<<"\n Name: "<<this->name<<endl;

cout<<"\n Marks: "<<marks<<endl;

};

int main() {

Student st[3]; //Array of Objects

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

cout<<" Enter Student "<<i+1<<" Record";

47
st[i].getDetail();

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

cout<<"\n Student "<<i+1<<endl;

st[i].displayInfo();

return 0;

48
49
18)Write a Program to demonstrate Call by Value

/*Program to demonstrate Call by Value*/

#include <iostream>

using namespace std;

void swap(int,int); //function prototype/declaration

int main() {

int a,b;

cout<<"\n Enter Value of A and B: ";

cin>>a>>b; //run-time/dynamic initialization

cout<<"\n Before Swapping ";

cout<<"\n\t A= "<<a;

cout<<"\n\t B= "<<b;

swap(a,b); //pass by value (a,b are actual arguments) function call

cout<<"\n Values of A and B (in main) After Returning from Swap function";

cout<<"\n\t A= "<<a;

cout<<"\n\t B= "<<b;

return 0;

void swap(int x,int y) { //copy of actual arguments are passed to dummy arguments i.e. x,y

int temp; //x=10 y=5

temp=x; //temp=10

x=y; //x=5

y=temp; //y=10

cout<<"\n After Swapping ";

50
cout<<"\n\t A= "<<x;

cout<<"\n\t B= "<<y;

51
19)Write a Program to demonstrate Call by Address

/*Program to demonstrate call by address*/

#include <iostream>

using namespace std;

void swap(int*,int*); //function prototype (pointers)

int main() {

int a,b;

cout<<"\n Enter Value of A and B: ";

cin>>a>>b;

cout<<"\n Before Swapping: ";

cout<<"\n\t A= "<<a;

cout<<"\n\t B= "<<b;

swap(&a,&b); //pass by address (addresses of actual arguments are passed)

cout<<"\n Values of A and B in main (After Swapping)";

cout<<"\n\t A= "<<a;

cout<<"\n\t B= "<<b;

return 0;

void swap(int *x,int *y) { //addresses of actual arguments are received by pointers i.e. *x,*y

int temp;

temp=*x;

*x=*y;

*y=temp;

}
52
53
20)Program to swap private data of two classes using Friend Function

/*Program to swap private data of two classes using friend function*/

#include <iostream>

using namespace std;

class yyy; //forward declaration

class xxx {

private:

int x;

public:

xxx(int xx) {

x=xx;

void display() {

cout<<"\n XXX Data: "<<x;

friend void swap(xxx&, yyy&); //friend function declaration

};

class yyy {

private:

int y;

public:

yyy(int yy) {

y=yy;
54
}

void display() {

cout<<"\n YYY Data: "<<y;

friend void swap(xxx&, yyy&); //friend function declaration

};

void swap(xxx &objx, yyy &objy) { //friend function definition

int temp;

temp=objx.x;

objx.x=objy.y;

objy.y=temp;

int main() {

xxx ob1(5);

yyy ob2(4);

cout<<"\n Before Swapping";

[Link]();

[Link]();

swap(ob1,ob2); //friend function will be invoked

cout<<"\n After Swapping";

[Link]();

[Link]();

return 0;

55
56
21)Write a Program to demonstrate Function Overloading

/*Program to demonstrate Function Overloading*/

#include <iostream>

using namespace std;

int sum(int,int);

int sum(int,int,int);

double sum(double,double);

double sum(int,double);

double sum(double,int);

int main() {

int a=7, b=6, c=4;

double x=5.2, y=17.6;

cout<<"\n Sum(int,int): "<<sum(a,b);

cout<<"\n Sum(int,int,int): "<<sum(a,b,c);

cout<<"\n Sum(double,double): "<<sum(x,y);

cout<<"\n Sum(int,double): "<<sum(a,y);

cout<<"\n Sum(double,int): "<<sum(x,b);

return 0;

int sum(int p,int q) {

return(p+q);

int sum(int p,int q,int r) {

57
return(p+q+r);

double sum(double p,double q) {

return(p+q);

double sum(int p,double q) {

return(p+q);

double sum(double p,int q) {

return(p+q);

58
22) Write a Program to demonstrate Constructor Overloading

/*Program to constructor overloading or multiple constructors*/

#include <iostream>

using namespace std;

class sample {

int a;

public:

sample() { //default or zero parameter constructor

cout<<"\n Default constructor Invoked ";

a=5;

sample(int x) { //single parameter-parameterized constructor

cout<<"\n Parameterized constructor with one parameter invoked";

a=x;

sample(int x,int y) { //two parameters-parameterized constructor

cout<<"\n Parameterized constructor with two parameters invoked";

a=x+y;

void display() {

cout<<"\n\t A: "<<a;

};

int main() {

59
cout<<"\n\t\t Demonstrating constructor overloading\n";

sample s1; //default constructor will be invoked

cout<<"\n S1 Object's Value ";

[Link]();

sample s2(14); //parameterized constructor with single parameter will be invoked

cout<<"\n S2 Object's Value ";

[Link]();

sample s3(13,11); //parameterized constructor with two parameters will be invoked

cout<<"\n S3 Object's Value ";

[Link]();

return 0;

60
23) Write a Program to demonstrate Inheritance

/*Program to demonstrate Inheritance/Derivation*/

#include <iostream>

using namespace std;

class Student { //Base Class or Parent Class

private: //Private members are not inheritable

string name;

int age;

public:

void inputDetails(){

cout<<"\n Enter Student Name: ";

getline(cin,name);

cout<<" Enter Student Age: ";

cin>>age;

void display(){

cout<<"\tStudent Details "<<endl;

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

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

};

class Report : public Student { //Sub Class or Child Class

private:

61
int sub1,sub2;

public:

void inputMarks(){

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

cin>>sub1;

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

cin>>sub2;

void studentReport(){

display();

cout<<"\tSubject 1 Marks: "<<sub1<<endl;

cout<<"\tSubject 2 Marks: "<<sub2<<endl;

};

int main() {

Report r1;

[Link]();

[Link]();

[Link]();

return 0;

62
63
24)Write a Program to demonstrate Public Inheritance/Derivation

/*Program to demonstrate Public Derivation/Inheritance*/

#include <iostream>

using namespace std;

class A {

private:

int x; //private members are not inheritable

public:

void inputX() {

cout<<" Enter Value of Base: ";

cin>>x;

int getX() {

return x;

};

class B:public A { //Public Derivation B is Derived Class

int y;

public:

void doubleBase() {

y=2 * getX();

cout<<"\n X: "<<getX();

cout<<"\n Y: "<<y;
64
}

};

int main() {

B b1;

[Link]();

[Link]();

return 0;

65
25)Write a Program to demonstrate Private Inheritance/Derivation

/*Program to demonstrate Private Inheritance*/

#include <iostream>

using namespace std;

class A { //base class

private:

int x; //private members are not inheritable

public:

void inputX() {

cout<<" Enter Value of Base: ";

cin>>x;

int getX() {

return x;

};

class B:private A { //Public Derivation/Inheritance

int y;

public:

void trippleBase() { //public base function (becomes private in derived)

inputX(); //Will be invoked here

y=3*getX();

cout<<"\n X: "<<getX();

cout<<"\n Y: "<<y;
66
}

};

int main() {

B b1;

//[Link](); //will give error

[Link]();

return 0;

67
26)Write a Program to demonstrate Protected Data Members

/*Program to demonstrate Protected Data Members*/

#include <iostream>

using namespace std;

class A { //base class

protected: //protected data member

int x;

public:

void inputX() {

cout<<" Enter Value of Base: ";

cin>>x;

};

class B:public A { //Derived Class

int y;

public:

void compute() {

y=x*x*x;

void display() {

cout<<"\n Base Value: "<<x;

cout<<"\n Cube of Base Value: "<<y;

}
68
};

int main() {

B obj;

[Link]();

[Link]();

[Link]();

return 0;

69
27)Write a Program to demonstrate Protected Inheritance/Derivation

/*Program to demonstrate Protected Inheritance*/

#include <iostream>

using namespace std;

class A { //base class

protected:

int x; //protected data member

public:

void inputX() {

cout<<"\n Enter Value of Base: ";

cin>>x;

};

class B:protected A { //Derived Class-Protected Derivation

int y;

public:

void compute() {

inputX();

y=x * x * x;

void display() {

cout<<"\n Base Value: "<<x;

cout<<"\n Cube of Base Value: "<<y;

}
70
};

int main() {

B obj;

//[Link](); ERROR-input() function is now protected in B Class

[Link]();

[Link]();

return 0;

71
28) Write a Program to demonstrate Single Inheritance

/*Program to demonstrate Single Inheritance*/

#include <iostream>

using namespace std;

class Square { //base class

protected:

int x; //protected data member

public:

void inputX(){

cout<<" Enter Value of Base Class: ";

cin>>x;

};

class Area:public Square { //public inheritance or derivation derived class

private:

int y; //private data member

public:

void computeArea(){

y=x * x;

cout<<"\n Side of Square: "<<x<<endl;

cout<<" Area of Square: "<<y<<endl;

};

int main() {
72
Area a1;

[Link]();

[Link]();

return 0;

73
29)Write a Program to demonstrate Multi-Level Inheritance

/*Program to demonstrate Multilevel Inheritance*/

#include <iostream>

using namespace std;

class Super { //Super Base Class

protected:

int x;

public:

void inputX(){

cout<<" Enter Base Data: ";

cin>>x;

};

class Intermediate:public Super { //Intermediate Base Class

protected:

int y;

public:

void inputY(){

cout<<" Enter Intermediate Base Data: ";

cin>>y;

};

class Sub:public Intermediate { //Derived Class

int z; //Private Data Member


74
public:

void computeSum(){

z = x + y;

cout<<"\n Sum of Super Base & Intermediate Base Data: "<<z;

};

int main() {

Sub s1;

[Link]();

[Link]();

[Link]();

return 0;

75
30)Write a Program to demonstrate Multiple Inheritance

/*Program to demonstrate Multiple Inheritance*/

#include <iostream>

using namespace std;

class A { //1st Base Class

protected:

int x;

public:

void inputX(){

cout<<"\n Enter 1st Base Data: ";

cin>>x;

};

class B { //2nd Base Class

protected:

int y;

public:

void inputY(){

cout<<" Enter 2nd Base Data: ";

cin>>y;

};

class C:public A,public B { //Multiple Inheritance

int z;
76
public:

void sum(){

z = x + y;

void display(){

cout<<"\n 1st Base Class Data: "<<x<<endl;

cout<<" 2nd Base Class Data: "<<y<<endl;

cout<<" Sum (in Derived Class): "<<z;

};

int main() {

C obj;

[Link]();

[Link]();

[Link]();

[Link]();

return 0;

77
31)Write a Program to to Handle Multiple Inheritance Ambiguity

/*Program to handle ambiguity in multiple inheritance*/

#include <iostream>

using namespace std;

class A { //1st Base Class

protected:

int x;

public:

void inputX(){

cout<<" Enter 1st Base Data: ";

cin>>x;

};

class B { //2nd Base Class

protected:

int x; //same data member as in 1st base class

public:

void inputX(){ //same member function as in 1st base class

cout<<" Enter 2nd Base Data: ";

cin>>x;

};

class C:public A,public B {

int z;
78
public:

void sum(){

z = A::x + B::x;

void display(){

cout<<"\n A Class Value: "<<A::x;

cout<<"\n B Class Value: "<<B::x;

cout<<"\n Sum (in C Class): "<<z;

};

int main(){

C obj;

obj.A::inputX();

obj.B::inputX();

[Link]();

[Link]();

return 0;

79
32)Write a Program to demonstrate Hierarchical Inheritance

/*Program to demonstrate Heirarchical Inheritance*/

#include <iostream>

using namespace std;

class A { //Base Class

protected:

int x; //protected data member

public:

void inputX(int val){

x=val;

};

class B:public A{ //1st Derived class with public derivation

int y; //private data member

public:

void square(){

y=x * x;

void display(){

cout<<"\n Base Class (1st Derived Class) ";

cout<<"\n Base Class Value: "<<x;

cout<<"\n Square of Base Value: "<<y<<endl;

};
80
class C:public A{ //2nd Derived class with public derivation

int z; //private data member

public:

void cube(){

z=x * x * x;

void display(){

cout<<"\n C Class (2nd Derived Class) ";

cout<<"\n Base Class Value: "<<x;

cout<<"\n Cube of Base Value: "<<z;

};

int main(){

B obj1;

[Link](7);

[Link]();

[Link]();

C obj2;

[Link](8);

[Link]();

[Link]();

return 0;

81
82
33)Consider a publishing company that markets both book and audio cassette version to
its works. Create a class Publication that stores the title (a string) and price (type float)
of a publication. Derive the following two classes from the above Publication class:
Book which adds a page count (int) and Tape which adds a playing time in
minutes(float). Each class should have getdata() function to get its data from the user
at the keyboard. Write the main() function to test the Book and Tape classes by
creating instances of them asking the user to fill in data with getdata() and
then displaying it using putdata().

/*Program to Derive three classes where Book class derived from Publication class and Tape class
derived from Publication class*/

#include <iostream>

using namespace std;

class Publication { //Base Class

protected:

string title; //protected data members

double price;

public:

void getData(){

cout<<"\n Enter Title: ";

getline(cin,title);

cout<<" Enter Price: ";

cin>>price;

};

class Book:public Publication{ //1st Derived class

int pageCount; //Private data member

public:

83
void inputPageCount(){

cout<<" Enter No. of Pages of Book: ";

cin>>pageCount;

void displayBookInfo(){

cout<<"\n Title of the Book: "<<title<<endl;

cout<<" Price of the Book: "<<price<<endl;

cout<<" Pages Count: "<<pageCount<<endl;

};

class Tape:public Publication { //2nd Derived class

double playingTime; //private data member

public:

void inputTime(){

cout<<" Enter Duration of the Tape: ";

cin>>playingTime;

void displayTapeInfo(){

cout<<"\n Title of the Tape: "<<title<<endl;

cout<<" Price of the Tape: "<<price<<endl;

cout<<" Playing Time of the Tape: "<<playingTime<<endl;

};

int main(){

84
Book b1;

cout<<" Enter Book Details ";

[Link]();

[Link]();

cout<<"\n\t Book Details ";

[Link]();

Tape t1;

[Link]();

cout<<"\n Enter Tape Details ";

[Link]();

[Link]();

cout<<"\n\t Tape Details ";

[Link]();

return 0;

85
86
34)Write a Program to demonstrate Hybrid Inheritance

/*Program to demonstrate Hybrid Inheritance*/

#include <iostream>

using namespace std;

class A { //Grand Parent class

protected:

int x;

public:

void inputX(){

cout<<" Enter Grand Parent Base Data: ";

cin>>x;

};

class B : public A { //Parent 1 class or B is derived from A

protected:

int y;

public:

void inputY(){

cout<<" Enter Parent 1 Base Data: ";

cin>>y;

};

class C { //Parent 2 class or C is Independent class

protected:

87
int z;

public:

void inputZ(){

cout<<" Enter parent 2 Base Data: ";

cin>>z;

};

class D : public B, public C { //D is derived from class B and class C (Multiple Inheritance)

public:

void sum(){

cout<<"\n Sum : "<<x+y+z;

};

int main(){

D obj;

[Link]();

[Link]();

[Link]();

[Link]();

return 0;

88
89
35)Write a Program to Resolve Hybrid Inheritance ambiguity Or Diamond Problem
using Virtual Base Class

/*Program to Resolve Hybrid Inheritance ambiguity Or Diamond Problem using Virtual Base Class*/

#include <iostream>

using namespace std;

class A { //Grand Parent class

protected:

int x; //Protected data member

public:

void inputX(){

cout<<" Enter Grand Parent Base Data: ";

cin>>x;

};

class B : virtual public A { //B is Derived from A virtually

protected: //using virtual all the members of A class will come in B class as virtually

int y; //Protected data member

public:

void inputY(){

cout<<" Enter Parent 1 Base Data: ";

cin>>y;

};

class C : virtual public A { //C is also Derived from A virtually

90
protected: //using virtual all the members of A class will come in C class as virtually

int z; //Protected data member

public:

void inputZ(){

cout<<" Enter Parent 2 Base Data: ";

cin>>z;

};

class D : public B, public C { //D is Derived from class B and class C (Multiple Inheritance)

public:

void sum(){

cout<<"\n Sum : "<<x+y+z;

};

int main(){

D obj; //Object of Derived class D

[Link]();

[Link]();

[Link]();

[Link]();

return 0;

91
92
36)Write a Program to compute Area of Right Angle Triangle, Equilateral Triangle,
Isosceles Triangle using function overloading

/*Program to compute Area of Right Angle Triangle, Equilateral Triangle, Isosceles Triangle using
Function Overloading*/

#include <iostream>

#include <math.h>

using namespace std;

float area(int);

float area(int,int);

float area(float,float);

int main(){

float ar,ht,bs;

int s1,s,b;

cout<<" Input the Side of Equilateral Triangle: ";

cin>>s1;

ar = area(s1); //Function call

cout<<" The Area of Equilateral Triangle is: "<<ar<<endl;

cout<<"-----------------------------------------------------------";

//-----------------------------------------------------------------------------------------------------------------
-

cout<<"\n Input the Side and Base of the Isosceles Triangle: ";

cin>>s>>b;

ar = area(s,b); //Function call

cout<<" The Area of Isosceles Triangle is: "<<ar<<endl;

cout<<"-----------------------------------------------------------";

93
//-----------------------------------------------------------------------------------------------------------------
-

cout<<"\n Input Height and Base of Right Angled Triangle: ";

cin>>ht>>bs;

ar = area(ht,bs); //Function call

cout<<" The Area of Right Angled Triangle is: "<<ar<<endl;

cout<<"-----------------------------------------------------------";

return 0;

//-----------------------------------------------------------------------------------------------------------------
-

float area(int s){

cout<<" Calculating the Area of the Equilateral Triangle\n";

float res = sqrt(3)/4*(s*s); //Area of Equilateral Triangle formula

return res;

//-----------------------------------------------------------------------------------------------------------------
-

float area(int x,int y){

cout<<" Calculating the Area of the Isosceles Triangle\n";

float ans = (float)(x*y/2); //Area of Isosceles Triangle formula

return ans;

//-----------------------------------------------------------------------------------------------------------------
-

float area(float height,float base){


94
cout<<" Calculating the Area of the Right Angled Triangle\n";

float ans=(0.5)*height*base; //Area of Right Angled Triangle formula

return ans;

//-----------------------------------------------------------------------------------------------------------------
-

95
37)Consider an example of declaring the examination result. Design three classes student,
exam and result. The student has data members such as rollno, name. Create the class
exam by inheriting the student class. The exam class adds data members representing
the marks scored in 5 subjects. Derive the result from exam-class and it has own data
members like total, average.

/*Program to show Examination Result by Deriving three classes*/

#include <iostream>

using namespace std;

class Student { //Grand Parent Class

protected:

int rollNo;

string name;

public:

void inputData() {

cout<<"\n Enter Student Name: ";

getline(cin,name);

cout<<" Enter Student Roll No. : ";

cin>>rollNo;

};

class Exam:public Student { //Parent Class

protected:

int s1,s2,s3,s4,s5;

public:

void getSubjectMarks() {

96
cout<<" Enter Marks of Five Subjects: ";

cin>>s1>>s2>>s3>>s4>>s5;

};

class Result:public Exam { //Child Class

private:

int total;

double avg;

public:

void CalculatePer() {

total=s1+s2+s3+s4+s5;

avg=((double)total/500)*100;

void display() {

cout<<"\n Student's Report Card "<<endl;

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

cout<<" Student Roll NO. "<<rollNo<<endl;

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

cout<<" Percentage: "<<avg;

};

int main() {

Result r1; //Object of Result Class

[Link]();

97
[Link]();

[Link]();

[Link]();

return 0;

98
38)Write a Program to demonstrate Unary Operator Overloading using Member
Function

/*Program to demonstrate Unary Operator overloading using Member function*/

#include <iostream>

using namespace std;

class sample {

int a,b; //Private Data members

char c;

public:

sample(){ //Default constructor

a=4;

b=6;

c='X';

void operator++(int x) /*Postfix ++, you can declare a member function


operator++() with one argument having type int. The compiler uses the int argument to distinguish
between the prefix and postfix increment/decrement operators. For implicit calls, the default value is
zero*/

a=a+1;

b=b+1;

void operator++(){ //prefix ++

a=a+1;

b=b+1;

99
}

void display(){

cout<<"\n Object Data Members Value A: "<<a<<" B: "<<b<<" C: "<<c;

};

int main(){

sample s1,s2; //Automatically Invokes Constructor function

cout<<"\n Objects Value Before Increment ";

[Link]();

[Link]();

++s1; //[Link]++();

s1++; //[Link]++(0);

++s2; //[Link]++();

cout<<"\n\n Objects Value After Increment ";

[Link]();

[Link]();

return 0;

100
39)Write a Program to demonstrate Unary Operator Overloading using Friend Function

/*Program to demonstrate Unary Operator Overloading using Friend Function*/

#include <iostream>

using namespace std;

class sample{

int a,b; //Private Data Members

public:

sample(){ //Default Constructor

a=54;

b=57;

friend void operator++(sample &obj){ //Pass By Reference

obj.a=obj.a+1;

obj.b=obj.b+1;

void display(){

cout<<" Object Value: "<<a<<" and "<<b<<endl;

};

int main(){

sample s1,s2; //automatically invokes constructor functions

cout<<" Objects Value Before Increment"<<endl;

[Link]();

101
[Link]();

++s1; //operator++(s1);

++s2; //operator++(s2);

++s2; //operator++(s2);

cout<<"\n Objects Value After Increment"<<endl;

cout<<" S1 Object"<<endl;

[Link]();

cout<<" S2 Object"<<endl;

[Link]();

return 0;

102
40)Write a Program to demonstrate Binary Operator Overloading using Member
Function

/*Program to demonstrate Binary Operator Overloading using member function*/

#include <iostream>

using namespace std;

class Sample {

int a,b;

public:

Sample(){ //Default Zero Parameter Constructor

a=0;

b=0;

Sample(int x,int y){ //Two Parameterized Constructor

a=x;

b=y;

Sample operator+(Sample obj){ //Using Member Function

Sample temp;

temp.a = a + obj.a;

temp.b = b + obj.b;

return temp;

void display(){

cout<<"\n Object Value: "<<a<<" and "<<b;

103
}

};

int main(){

Sample s1(15,15),s2(24,30),s3;

cout<<"\n Objects Values ";

[Link]();

[Link]();

s3 = s1 + s2; //[Link]+(s2); L.H.S + R.H.S

cout<<"\n\n Addition Result ";

[Link]();

return 0;

104
41)Write a Program to demonstrate Binary Operator Overloading using Friend Function

/*Program to demonstrate Binary Operator Overloading using Friend function*/

#include <iostream>

using namespace std;

class Sample {

int a,b;

public:

Sample(){ //Default Zero Parameter Constructor

a=0;

b=0;

Sample(int x,int y){ //Two Parameterized Constructor

a=x;

b=y;

friend Sample operator+(Sample obj1,Sample obj2){ //Using Member Function

Sample temp;

temp.a = obj1.a + obj2.a;

temp.b = obj1.b + obj2.b;

return temp;

void display(){

cout<<"\n Object Value: "<<a<<" and "<<b;

}
105
};

int main(){

Sample s1(20,15),s2(28,60),s3;

cout<<"\n Obects Values ";

[Link]();

[Link]();

s3 = s1 + s2; //operator+(s1,s2);

cout<<"\n\n Addition Result ";

[Link]();

return 0;

106
42)Write a Program to Concatenate Two Strings Objects using Binary Operator (+)
Overloading

/*Program to Concatenate Two string objects using Binary Operator(+) Overloading*/

#include <iostream>

#include <string.h>

using namespace std;

class AddString {

string str;

public:

AddString(){

str = "";

AddString(string temp){

str = temp;

AddString operator+(AddString obj){

AddString temp;

[Link] = str + [Link];

return temp;

void display(){

cout<<str;

};

107
int main(){

//Declaring two strings

string str1, str2;

cout<<"\n Enter 1st String: ";

cin>>str1;

cout<<" Enter 2nd String: ";

cin>>str2;

AddString a1(str1);

AddString a2(str2);

AddString a3; //Default Constructor will be invoked

a3 = a1 + a2; //[Link]+(a2);

cout<<"\n 1st String: "; [Link]();

cout<<"\n 2nd String: "; [Link]();

cout<<"\n Concatenated String: "; [Link]();

return 0;

108
43)Write a Program of Operator Overloading when Friend function is Compulsory

/*Program of Overloading when Friend function is compulsory*/

#include <iostream>

using namespace std;

class Sample {

int a,b;

public:

Sample(){ //Default Zero Parameter Constructor

a=0;

b=0;

Sample(int x,int y){ //Two Parameterized Constructor

a=x;

b=y;

friend Sample operator+(int ele,Sample obj){

Sample temp;

temp.a = obj.a + ele;

temp.b = obj.b + ele;

return temp;

void display(){

cout<<"\n Object Value: "<<a<<" and "<<b;

}
109
};

int main(){

Sample s1(21,14),s2;

cout<<"\n Obects Values ";

[Link]();

s2 = 5 + s1; //operator+(5,s1); [Link]+(s1)

cout<<"\n\n After Scalar Addition with 5 ";

[Link]();

return 0;

110
44)Write a Program to illustrate concept of Virtual Functions

/*Program to Illustrate the Concept of Virtual Funcitons*/

#include <iostream>

using namespace std;

class Base { //Base Class

public:

virtual void show(){

cout<<" Show Base Class "<<endl;

};

class Derived1 : public Base { //1st Derived class

public:

void show(){

cout<<" Show 1st Derived Class "<<endl;

};

class Derived2 : public Base { //2nd Derived class

public:

void show(){

cout<<" Show 2nd Derived Class "<<endl;

};

int main() {

Base *ptr; //Object Pointer


111
Base b1; //[Link]();

ptr = &b1;

ptr->show();

Derived1 d1;

ptr = &d1;

ptr->show(); //Dynamic Linkage

Derived2 d2;

ptr = &d2;

ptr->show(); //Dynamic Linkage

return 0;

112
45)Write a Program to demonstrate Runtime Polymorphism

/*Program to demonstrate Runtime Polymorphism*/

#include <iostream>

#include <conio.h>

using namespace std;

class Shape {

protected:

int width, height;

public:

Shape(int x, int y){ //Parameterized Constructor

width=x;

height=y;

virtual void area(){

cout << "Parent Class Area :" <<endl;

};

class Rectangle : public Shape {

public:

Rectangle(int a, int b):Shape(a,b){

//constructor with default arguments & initializer list

void area(){

cout << " Rectangle Class Area :" <<width*height<<endl;


113
}

};

class Triangle: public Shape {

public:

Triangle(int a,int b):Shape(a,b){

void area(){

cout << " Triangle Class Area :" <<(width * height)/ 2;

};

int main(){ // Main function for the program

Shape *shape;

Rectangle rec(5,6);

Triangle tri(10,12);

int op;

cout<<"\n RUN TIME POLYMORPHISM\n";

cout<<"\n Enter 1 to Calculate Area of Rectangle OR\n"" Enter 2 to Calculate Area of Triangle:
";

cin>>op;

if(op==1){ // store the address of Rectangle

shape = &rec;

else if(op==2){ // store the address of Triangle

shape = &tri;
114
}

else {

cout<<"Incorrect Option: "<<op;

cout<<"\n Try Again!!";

shape->area();

return 0;

115
46)Write a Program to demonstrate Manipulators

/*Program to demonstrate Manipulators*/

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

// Dog Age in Human years ([Link])

cout << setw(10) << left << "Dog Age" << "|";

cout << setw(12) << right << "Human Age" << endl;

// Produce Long line

cout << setfill('-') << setw(23) << "" << endl;

// Reset Fill Character back to space

cout << setfill(' ');

cout << setw(10) << left << "2 Months" << "|";

cout << setw(12) << right << "14 Months" << endl;

cout << setw(10) << left << "6 Months" << "|";

cout << setw(12) << right << "5 Years" << endl;

cout << setw(10) << left << "8 Months" << "|";

cout << setw(12) << right << "9 Years" << endl;

cout << setw(10) << left << "1 Year" << "|";

cout << setw(12) << right << "15 Years" << endl;

116
// Produce Long line

cout << setfill('-') << setw(23) << "" << endl;

return 0;

117
47)Write a Program to Create (Open and Close) a Empty File

/*Program to Create (Open & Close) a Empty File*/

#include <iostream>

#include <fstream>

using namespace std;

int main() {

fstream new_file;

new_file.open("[Link]",ios::out); //opening file after creation

if(!new_file){

cout<<"File Creation Failed ";

else {

cout<<"New File successfully Created ";

new_file.close(); //Closing file

return 0;

118
48)Write a Program to Write data into a File

/*Program to Write Data into a File*/

#include <iostream>

#include <fstream>

using namespace std;

int main() {

ofstream new_file;

new_file.open("[Link]");

if(!new_file){

cout<<"file creation failed ";

else{

cout << "\n new file created successfully ";

new_file << "learning file handling"<<endl; //Writing to a File

new_file<<"I am loving It"<<endl;

new_file<<"It is very easy to learn";

new_file.close(); //Closing File

return 0;

119
49)Write a Program to Read data from a File

/*Program to Read Data from a File*/

#include <iostream>

#include <fstream>

using namespace std;

int main() {

ifstream new_file;

new_file.open("[Link]");

if(!new_file){

cout<<"No Such File";

else{

char str[40];

while(!new_file.eof()){

new_file.getline(str,40); // Reading Data from a File (line by line)

cout<<str<<endl;

new_file.close();

return 0;

120
50)Write a Program to Append data into a File

/*Program to Append Data into a File*/

#include <iostream>

#include <fstream>

using namespace std;

int main() {

ofstream new_file;

new_file.open("[Link]",ios::app); //Writing Data at the end (Append mode)

if(!new_file) {

cout<<"File Creation FAILED";

else {

cout<<"Adding data to existing file";

new_file<<endl<<"It is safe and secure";

new_file.close();

return 0;

121
122

You might also like