Professional Documents
Culture Documents
Bca Oop
Bca Oop
The C++ is an object oriented programming (OOP) language. The OOP language offers many features
in programming which reduces the programmer’s complexity and the code reusability facility while writing
the large size program i.e. the program having more than thousand lines of coding. The OOP is just an
approach (a way of) to write the programs easily among different types of programming approach. We can
have following types of programming approaches:
Member Functions
cout<<”Enter the length and breadth of the rectangle:”;
cin>>l>>b;
Class
}
void area()
{
ar=l*b;
cout<<”The Area is:”<<ar;
}
void perimeter()
{
p=2*(l+b);
cout<<”The Perimeter is:”<<p;
}
};
void main()
{ Object/Instance of the class Rectangle
Rectangle r;
clrscr();
r.input();
r.area();
r.perimeter();
getch();
}
Ex: you can use the same class program for No. of Rectangle objects by taking an array of objects
# include <iostream.h>
# include <conio.h>
class Rectangle
{
float l,b,ar,p;
public:
void input()
{
cin>>l>>b;
}
void area()
{
ar=l*b; cout<<"The Area is:"<<ar;
}
void perimeter()
{
p=2*(l+b); cout<<"\nThe Perimeter is:"<<p;
}
};
void main()
{
Rectangle r[10];
clrscr();
int i;
for(i=0;i<=4;i++)
{
cout<<"\nEnter the length and breadth of Rectangle No."<<i+1<<":";
r[i].input();
}
for(i=0;i<=9;i++)
{
cout<<"\nWhat you want for Rectangle No."<<i+1<<":";
cout<<"\nEnter:\n1-> Area\n2->Permiter\n3->Both\n4->None:";
int ch;
cin>>ch;
if(ch==1)
r[i].area();
else if(ch==2)
r[i].perimeter();
else if(ch==3)
{
r[i].area(); r[i].perimeter();
}
else
cout<<"Invalid choice";
}
getch();
}
Designing of Class:
As a class defines the common attributes in form of variables, called as data members and common
behaviors in form of functions, called as member functions or methods of similar kind of objects, so while
we define a class program to be used by its No. of representatives/objects, so we always be concerned
about the data members and member functions of a class. Hence a class can have two components such as:
Data members and Member functions. As such a class can have only the data members or only the
member functions or both or none.
Also we should be concerned about the members’ visibility or accessibility with their scopes which
are defined by some access specifiers like private, public, protected.
Access Specifiers:
An access specifier specifies the members of class as which members will be accessible outside of
the class, only inside the class and among the objects of the class. These specification is defined by three
access specifiers. Those are:
i. Private Access Specifier: This specifier specifies the members of a class as private i.e. the private
members can’t be accessible outside of the class. Only the class members inside the can access
those. In OOP mostly the data members are kept as private. The private member of a class can only
be accessible to its friend class or friend member function.
ii. Protected Access Specifier: The protected members are having accessing scope same as to private
members but it can be accessible by sub-class or child class of an existing class under inheritance.
iii. Public Access Specifier: The public members can be accessible by any part of coding of program and
anywhere. i.e. public members are accessible by all and anywhere at any place.
Q: ______Public_____ members have very less/no restriction on their accessing.
Q: _____Private______ members can have most/highest restriction on their accessing.
Q: ___Protected______ members of a class have more restriction than the public and less restriction than
private on their accessing.
Q: Which members are available to the inherited or to subclass of a class.
Ans. both protected and public members
Q: If you don’t specify any access specifier for a member the it will go under ___private__ access specifier.
Q: Which one is the default access specifier of a class? Ans. private
Q: Demonstrate a program in OOP about the access specifiers of members to make addition of any two
numbers.
# include <iostream.h>
# include <conio.h>
class Addition
{
private:
float a,b;
public:
float c;
void Add()
{
cout<<"Enter any two numbers:";
cin>>a>>b;
c=a+b;
cout<<"The addition is:"<<c;
}
protected:
float d;
};
To write a valid C++ statements, what are necessary elements required are known as the C++ tokens.
C++ Tokens:
The tokens are the basic building blocks used to write a valid c++ statement. These are the unitary
elements with the combination of which a c++ statement is written.
Generally, we can have the 6 types token in C++. Those are
i. Key words ii. Literals iii. Identifiers iv. Operators v. Separators vi. Comments
For Ex: int x=20;
Key Words:
Keywords (also known as reserved words) have special meanings to the C++ compiler and are
always written or typed in short (lower) cases. Keywords are words that the language uses for a special
purpose, such as void, int, public, etc. It can’t be used for a variable name or function name or any other
identifiers. The total count of reserved keywords is 95. Below is the table for some commonly used C++
keywords.
C++ Keyword
asm double new switch
auto else operator template
break enum private this
case extern protected throw
catch float public try
char for register typedef
class friend return union
const goto short unsigned
continue if signed virtual
default inline sizeof void
delete int static volatile
do long struct while
Literals / Constants:
Read from ‘C’ notes.
Identifiers:
Read from ‘C’ notes. In C++, we can have following identifiers:
i. Class Name Identifier
ii. Object name Identifier
iii. Function/Method name Identifier
iv. Variable name identifier. (You read this one in complete from ‘C’ Notes)
Operators:
Read from ‘C’ notes. The extra operator ‘new’ will be discussed later.
Separators:
(), {},[], , ,;, blank space/ White space etc.
Comments:
// -> it is single line comment
/* …. .. */ -> it is multiline comments
Generally the comments are used to write the user description regarding a code segment, to which
the compiler does not execute that means the comments are ignored by the compiler. Also if user wants to
keep some C++ statements for future use and will not executed for present time are kept in comments: For
example:
void main()
{
int x,y,z=30; //int x=y=z=30; (int x=y=z=30; kept as a single line comment)
//During the declaration time of variables, the multiple assignment can’t be possible
/*
The statement int x=y=z=30; will show error, because when 30 will go to be initialized
the left side variable which is a one variable as x=y=z
but the symbols are not allowed in the variable name, so it shows error */
cout<<”The value of z is:”<<z;
}
Then by using a simple cout stream we may not be able to format the output as shown above. Hence we
can use the setw function from <iomanip> header, and we can set the specific width between the elements.
This way we can make the program output to look more realistic and presentable. <iomanip> header
contains several functions to format the output. The most commonly used functions of <iomanip> header
file are as follows:
Setprecision: This function sets the precision for decimal or float values.
Example:
#include <iostream.h>
#include <iomanip.h>
# include <conio.h>
void main ()
{
double float_value =3.14159;
int fixed=456;
clrscr();
cout <<"Precesion is set to 4:"<< setprecision(4) << float_value << '\n';
cout <<"Precesion is set to 9:"<< setprecision(9) << float_value << '\n';
cout << fixed<<endl;
cout <<"Precesion is set to 5:"<<setprecision(5) << float_value << '\n';
cout <<"Precesion is set to 10:"<< setprecision(10) << float_value << '\n';
getch();
}
Output:
Setfill: Setfill function is used to fill the stream with char type c specified as a parameter.
Example:
#include <iostream.h>
#include <iomanip.h>
void main ()
{
cout << setfill ('*') << setw (10);
cout << 15 << endl;
cout << setfill ('#') << setw (5);
cout << 5 << endl;
cout << setfill ('#') << setw (5);
cout << 1 << endl;
cout << setfill ('*') << setw (10);
cout << 25 << endl;
}
Output:
setbase(): It is used to sets the basefield to one of its possible values: dec, hex or oct, according to
argument base.
Declaration:
setbase (int base);
Example:
#include <iostream.h>
#include <iomanip.h>
void main ()
{
cout <<setbase(16); cout << 110 << endl;
}
Output: 6e
Classes within Classes (Nested Class):
C++ permits declaration of a class within another class. A class is declared as a member of another
class is called as a nested class or a class within another class. The name of a nested class is local to the
enclosing class. The nested class is in the scope of its enclosing class. For example:
# include <iostream.h>
# include <conio.h>
class StudentInfo
{
private:
int Rollno;
char Gender;
char Name[31];
public:
void Getdata()
{
cout<<"Enter the Rollno:";
cin>>Rollno;
cout<<"Enter the Name:";
cin>>Name;
cout<<"Enter the Gender:";
cin>>Gender;
}
void Display()
{
cout<<"\nName\tRollNo.\tGender\tDate of Birth\n";
cout<<"------------------------------------------"<<endl;
cout<<Name<<"\t"<<Rollno<<"\t"<<Gender<<"\t";
}
class Date
{
private:
int dd,mm,yy;
public:
void Getdate()
{
cout<<"Enter the date of Birth as DD MM YY:";
cin>>dd>>mm>>yy;
}
void Showdate()
{
cout<<dd<<"/"<<mm<<"/"<<yy;
cout<<"\n-----------------------------------------";
}
};
};
void main()
{
clrscr();
StudentInfo Sobj;
StudentInfo::Date Dobj;
Sobj.Getdata();
Dobj.Getdate();
Sobj.Display();
Dobj.Showdate();
getch();
}
Pure/Accessor Functions: These are used to return the information of an object’s current state. Ex. const
member function or static member function. This function is only concerned with
return type value and can’t modify the object’s data member.
Ex.:
# include <iostream.h>
# include <conio.h>
class Pure
{
int x,y;
public:
Pure(int a,int b)
{
x=a;y=b;
}
void Disp() const
{
//x=x+5; y=y+5; //Here it shows error, as Disp() function is a constant function means it is a pure
cout<<"x="<<x<<" and " <<"y="<<y; // function and can’t modify the data members of the object
}
int Add() // Here, the Add() function is also a pure function as it is concerned only with return type
{
return x+y;
}
};
void main()
{
clrscr();
Pure P(10,20);
P.Disp();
cout<<"\nThe Addition of two data members of this object is:"<<P.Add()<<endl; getch();
}
Output:
Impure/Mutator/Implementer Function: These are used to make modification to the data members. The
implementer functions are one of the key concepts in defining the data hiding and
data encapsulation. For example:
# include <iostream.h>
# include <conio.h>
class Circle
{
private:
float r,Ar;
public:
void CArea() //Here, the function CArea() is a mutator/impure/implementer function
{
cout<<"Enter the radius of a circle:";
cin>>r;
Ar=3.14*r*r;
cout<<"The Area of the circle is:"<<Ar;
r=r*2;
cout<<"\nIt's Diameter is:"<<r;
}
};
void main()
{
clrscr();
Circle C;
C.CArea();
getch();
}
Output:
double Box::getVolume()
{
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before :: operator. A
member function will be called using a dot operator (.) on an object where it will manipulate data related to
that object only. For example:
#include <iostream.h>
# include <conio.h>
class Box
{
private:
double length;
double breadth;
double height;
public:
void setLength( double len )
{ length=len; }
void setBreadth( double brd )
{
breadth=brd;
}
void setHeight( double ht );
double getVolume(void);
};
double Box::getVolume()
{
return length * breadth * height;
}
void main()
{
Box Box1;
Box Box2;
double L,B,H,volume = 0.0;
clrscr();
cout<<”Enter the length, breadth and height of the box1:”;
cin>>L>>B>>H;
Box1.setLength(L);
Box1.setBreadth(B);
Box1.setHeight(H);
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
Constructors in C++:
A constructor in C++ is a special type member function/method that is invoked automatically at
the time of object creation. Generally, it is used to initialize the data members of new objects. The
constructor in C++ has the same name as the class name or structure. Constructor is invoked at the time
of object creation. It constructs the values i.e. provides data for the object, that’s why it is known as
constructors. The following rules are used for a constructor member function.
• Constructor is a member function of a class, whose name is same as to its class name. (imp. point)
• Constructor is a special type of member function that is used to initialize the data members for an
object of a class automatically, when an object of the same class is created.
• Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.
• Constructor does not return value, hence it does not have any return type not even if void. (imp. Point)
Types of Constructors:
We can have 3 types of Constructors in C++.
1. Default Constructor
A constructor with no arguments (or parameters) in the definition of constructor, is a default constructor.
It is the type of constructor in C++ usually used to initialize data members (variables) with real values. For
Example”
# include <iostream.h>
# include <conio.h>
class Employee
{
private:
int Eno,Age;
char *Name;
float Salary;
char Gender;
public:
Employee()
{
Eno=0;
Age=0;
Name="";
Salary=0.0;
Gender='M';
}
void Display()
{
cout<<"\nEmp No.:"<<Eno;
cout<<"\nName:"<<Name;
cout<<"\nAge:"<<Age;
cout<<"\nGender:"<<Gender;
cout<<"\nSalary:"<<Salary;
}
};
void main()
{
clrscr();
Employee Emp;
Emp.Display();
getch();
}
Output:
2. Parameterized Constructor
Unlike the Default constructor, It contains parameters (or arguments) in the constructor definition and
declaration. More than one argument can also pass through a parameterized constructor. For Example:
# include <iostream.h>
# include <conio.h>
class Employee
{
private:
int Eno,Age;
char *Name;
float Salary;
char Gender;
public:
Employee(int Empno, char *Nm,char G,int ag,float Sal)
{
Eno=Empno;
Age=ag;
Name=Nm;
Salary=Sal;
Gender=G;
}
void Display()
{
cout<<"\nEmp No.:"<<Eno;
cout<<"\nName:"<<Name;
cout<<"\nAge:"<<Age;
cout<<"\nGender:"<<Gender;
cout<<"\nSalary:"<<Salary;
}
};
void main()
{
clrscr();
int En,Ag;
char *Nm;
char G;
float Sal;
cout<<"\nEnter the following details of an Employee:"<<endl;
cout<<"Employee Number:"; cin>>En;
cout<<"Employee's Name:"; cin>>Nm;
cout<<"Employee's Gender:"; cin>>G;
cout<<"Employee's Age:"; cin>>Ag;
cout<<"Employee's Salary:"; cin>>Sal;
Employee Emp(En,Nm,G,Ag,Sal);
Emp.Display();
getch();
}
Output:
3. Copy Constructor
A copy constructor is the constructor in C++ which allows a member function to initialize an object
using another object of the same class. It helps to copy data from one object to another. For Example:
# include <iostream.h>
# include <conio.h>
class Employee
{
private:
int Eno,Age;
char *Name;
float Salary;
char Gender;
public:
Employee(int Empno, char *Nm,char G,int ag,float Sal)
{
Eno=Empno;
Age=ag;
Name=Nm;
Salary=Sal;
Gender=G;
}
Employee(Employee &obj)
{
Eno=obj.Eno;
Age=obj.Age;
Name=obj.Name;
Salary=obj.Salary;
Gender=obj.Gender;
}
void Display()
{
cout<<"\nEmp No.:"<<Eno;
cout<<"\nName:"<<Name;
cout<<"\nAge:"<<Age;
cout<<"\nGender:"<<Gender;
cout<<"\nSalary:"<<Salary;
}
};
void main()
{
clrscr();
int En,Ag;
char *Nm;
char G;
float Sal;
cout<<"\nEnter the following details of an Employee:"<<endl;
cout<<"Employee Number:"; cin>>En;
cout<<"Employee's Name:"; cin>>Nm;
cout<<"Employee's Gender:"; cin>>G;
cout<<"Employee's Age:"; cin>>Ag;
cout<<"Employee's Salary:"; cin>>Sal;
Employee Emp1(En,Nm,G,Ag,Sal);
Emp1.Display();
Employee Emp2=Emp1;
// Emp2=Emp1;
cout<<"\n\nThe data of second employee:\n";
Emp2.Display();
getch();
}
Output:
Constructor Overloading:
In C++, if we define more than one constructor but with different list of arguments, then it is
known as constructor overloading. This concept is quite similar to function overloading.
Overloaded constructors essentially have the same name (exact name of the class) and
different by number and type of arguments.
A constructor is called depending upon the number and type of arguments passed.
While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.
For Example:
# include <iostream.h>
# include <conio.h>
class Employee
{
private:
int Eno;
char *Name;
int Age;
char Gender;
float Salary;
public:
Employee()
{
Eno=0;
Name="";
Age=0;
Gender='M';
Salary=0.0;
}
Employee(int Empno, char *Nm,char G,int ag,float Sal)
{
Eno=Empno;
Age=ag;
Name=Nm;
Salary=Sal;
Gender=G;
} If you don’t design the copy constructor, then the copy constructor is
Employee(Employee &obj) automatically generated while you assign an object to another object of
{ same class and it assigns the value of all data members of the existing
Age=obj.Age; object to the new object. If you design the copy constructor with less
Gender=obj.Gender; number of data member assignment, then also the value of all data
Salary=obj.Salary; members of assigning object are assigned to the new object.
}
void Update(int En,char *Nm)
{
Eno=En;
Name=Nm;
}
void Display()
{
cout<<"\nEmp No.:"<<Eno;
cout<<"\nName:"<<Name;
cout<<"\nAge:"<<Age;
cout<<"\nGender:"<<Gender;
cout<<"\nSalary:"<<Salary;
}
};
void main()
{
clrscr();
int En,Ag;
char *Nm;
char G;
float Sal;
cout<<"\nEnter the following details of an Employee:"<<endl;
cout<<"Employee Number:"; cin>>En;
cout<<"Employee's Name:"; cin>>Nm;
cout<<"Employee's Gender:"; cin>>G;
cout<<"Employee's Age:"; cin>>Ag;
cout<<"Employee's Salary:"; cin>>Sal;
Employee Emp1(En,Nm,G,Ag,Sal);
cout<<"\nThe data of first employee:\n";
Emp1.Display();
Employee Emp2;
cout<<"\n\nThe data of second employee after first creattion:\n";
Emp2.Display();
Emp2=Emp1;
cout<<"\n\nThe data of second Employee after the copy:";
Emp2.Display();
cout<<"\nEnter the Employee No. of Second Employee:";
cin>>En;
cout<<"Enter the name of second Employee:";
cin>>Nm;
Emp2.Update(En,Nm);
cout<<"The data of second Employee after update:";
Emp2.Display();
getch();
}
Output:
Destructor:
Destructor is an instance member function which is invoked automatically whenever an object is
going to be destroyed. Meaning, a destructor is the last function that is going to be called before an
object is destroyed.
Destructor is also a special member function like constructor. Destructor destroys the class objects
created by constructor.
Destructor has the same name as their class name preceded by a tilde (~) symbol.
It is not possible to define more than one destructor.
The destructor is only one way to destroy the object created by constructor. Hence destructor can-
not be overloaded.
Destructor neither requires any argument nor returns any value.
It is automatically called when object goes out of scope.
Destructor release memory space occupied by the objects created by constructor.
In destructor, objects are destroyed in the reverse of an object creation.
For Example:
#include<iostream.h>
# include<conio.h>
int count=0;
class DTest
{
public:
DTest()
{
count++; cout<<"\n No. of Object created:\t"<<count;
}
~DTest()
{
cout<<"\n No. of Object destroyed:\t"<<count; --count;
}
};
main()
{
clrscr();
DTest t,t1,t2,t3;
Getch();
}
Output
No. of Object created: 1
No. of Object created: 2
No. of Object created: 3
No. of Object created: 4
No. of Object destroyed: 4
No. of Object destroyed: 3
No. of Object destroyed: 2
No. of Object destroyed: 1
Inline Member Function:
The keyword inline is used as a function specifier only in function definition is treated as an inline
function. C++ provides inline functions to reduce the function call overhead. An inline function is a
function that is expanded in line when it is called. When the inline function is called only code of the
inline function gets inserted or substituted at the point of the inline function call. This s ubstitution is
performed by the C++ compiler at compile time. An inline function may increase efficiency if it is small.
void WaterBill::Calculate()
{
if(Units<=500)
Billamount=Units*2;
else if(Units>500 && Units<=800)
Billamount=500*2+(Units-500)*3;
else if(Units>800 && Units<=1000)
Billamount=500*2+300*3+(Units-800)*4;
else
Billamount=500*2+300*3+200*4+(Units-1000)*5;
cout<<"\nThe total amount of water bill to pay Rs. "<<Billamount<<"by consumer No.:"<<CNo;
}
void main()
{
clrscr();
WaterBill WB;
WB.getUnits();
WB.Calculate();
getch();
}
Output:
Q: WAP to make addition of any two integers, floats, characters and strings, since here all the operations
have same action but with different data type, so apply the method overloading concept with same
name.
Ans.
# include <iostream.h>
# include <conio.h>
# include <string.h>
class Overload
{
public:
void Add(int x, int y)
{
cout<<"\nThe addition of "<<x<<"+"<<y<<" is:"<<(x+y);
}
void Add(float x, float y)
{
cout<<"\nThe addition of "<<x<<"+"<<y<<" is:"<<(x+y);
}
void Add(char x, char y)
{
cout<<"\nThe addition of "<<x<<"+"<<y<<" is:"<<(char)(x+y);
}
void Add(char x[], char y[])
{
cout<<"\nThe addition of "<<x<<"+"<<y<<" is:"<<strcat(x,y);
}
};
void main()
{
clrscr();
int a,b;
float c,d;
char e,f;
char g[31],h[31];
cout<<"Enter any two Integers:"; cin>>a>>b;
cout<<"Enter any two floating numbers:"; cin>>c>>d;
cout<<"Enter any two single characters:"; cin>>e>>f;
cout<<"Enter any two strings:"; cin>>g>>h;
Overload OV;
OV.Add(a,b); OV.Add(c,d); OV.Add(e,f); OV.Add(g,h);
getch();
}
Output:
Q: WAP to enter the Roll No., Name and Percentage of Marks for 10 students then allow the user to search
the record of a student either by their Roll Nos. or by their Names or by their percentage of marks.
# include <iostream.h>
# include <conio.h>
# include <string.h>
class Student
{
private:
int RLN; char Name[31]; float Per;
public:
void Input()
{
cin>>RLN; cin>>Name; cin>>Per;
}
int Search(int Roll)
{
if(RLN==Roll)
return 1;
else
return 0;
}
int Search(char *NM)
{
if(strcmp(Name,NM)==0)
return 1;
else
return 0;
}
int Search(float P)
{
if(Per==P)
return 1;
else
return 0;
}
void Display()
{
cout<<"\n"<<RLN<<"\t"<<Name<<"\t"<<Per;
}
};
void main()
{
clrscr();
int RollNo,i,ch, found=0; float per; char Nm[31],Ans;
Student Std[10];
cout<<"Enter the followings for 10 students:"; cout<<"\nRollNo. Name Percentage\n";
for(i=0;i<=9;i++)
{
Std[i].Input();
}
cout<<"Press Y/y to continue the search:"; cin>>Ans;
while(Ans=='Y' || Ans=='y')
{
cout<<"1->Search by Roll No."; cout<<"\t2->Search by Name";
cout<<"\t3->Search by Percentage"; cout<<"\nEnter your choice:"; cin>>ch;
if(ch==1)
{
cout<<"Enter the Roll no.:"; cin>>RollNo;
for(i=0;i<=9;i++)
{
if(Std[i].Search(RollNo))
{
cout<<"\nIt is found in "<<(i+1)<<" position:"; Std[i].Display(); found=1;
}
}
if(found==0)
cout<<"\nThe Record is not found";
}
else if(ch==2)
{
cout<<"Enter the Name:"; cin>>Nm;
for(i=0;i<=9;i++)
{
if(Std[i].Search(Nm))
{
cout<<"\nIt is found in "<<(i+1)<<" position:"; Std[i].Display(); found=1;
}
}
if(found==0)
cout<<"\nThe Record is not found";
}
else if(ch==3)
{
cout<<"Enter the Percentage:"; cin>>per;
for(i=0;i<=9;i++)
{
if(Std[i].Search(per))
{
cout<<"\nIt is found in "<<(i+1)<<" position:"; Std[i].Display(); found=1;
}
}
if(found==0)
cout<<"\nThe Record is not found";
}
else
cout<<"\nInvalid Choice";
cout<<"\nPress Y/y to continue the search:";
cin>>Ans;
}
clrscr();
cout<< "\nThe records of 10 students are as follows:";
cout<<"\nRollNo. Name Percentage";
cout<<"\n-----------------------------";
for(i=0;i<=9;i++)
Std[i].Display();
cout<<"\nThank You!";
getch();
}
Output:
Operator Overloading:
When an existing operator is used with a special meaning beyond of its original meaning but
without changing its original meaning is known as operator overloading. Operator overloading is a
compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without
changing its original meaning. Through operator overloading we can change the way of operators’ actions
beyond of their original actions. In C++, we do operator overloading for user-defined classes or
structures. Operator overloading helps to perform various operations on objects of user defined classes
or data types. For example:
Suppose, you have a box object from a Box class for measuring its cubic volume, then you need to
multiply its length, breadth and height. But what you have to do if you want the volume of same box by
increasing the length, breadth and height with 1 unit each. Definitely you will need a member function
for increasing 1 unit each side and then have to call the volume() member function. Here two things will
come to your mind, one is whether will you prefer to call Box1.Increase() or prefer to write Box1++.
Definitely you will prefer the operator notation with the objet as an operand. But the ++ is acted on
primitive numeric data type and can’t act on an object because it is created from a user defined class. If
you give the ability to ++ operator to act on the object’s data members by giving the object itself as its
operand, then ++ operator is to be overloaded by writing a member function for it by which its original
operation will remain same but it will work on object beyond of its original operation. Similarly, you can
do operator overloading for binary operators to write arithmetical expression on objects to get the result
in form of object. The advantage of Operators overloading is to perform different operations on the same
object type operands.
Rules for Operator Overloading
Existing operators can only be overloaded, but the new operators cannot be overloaded.
The overloaded operator contains at least one operand of the user-defined data type.
We cannot use friend function to overload certain operators. However, the member function can be
used to overload those operators.
When unary operators are overloaded through a member function take no explicit arguments, but,
if they are overloaded by a friend function, takes one argument.
When binary operators are overloaded through a member function takes one explicit argument, and
if they are overloaded through a friend function takes two explicit arguments.
Operators that can be overloaded Examples
Binary Arithmetic +, -, *, /, %
Unary Arithmetic +, -, ++, —
Assignment =, +=,*=, /=,-=, %=
Bitwise & , | , << , >> , ~ , ^
De-referencing (->)
Subscript []
Function call ()
Logical &, | |, !
Relational >, < , = =, <=, >=
Operators that cannot be overloaded are as follows:
Scope operator (::)
sizeof
member selector(.)
member pointer selector(*)
ternary operator(?:)
Q: WAP to have a Box object and then find out its cubic volume. After this find its cubic volume by
increasing 2 units of its each attribute. Again create second Box object which is the double size of first
object. At last create the third Box object by the expression ((Box1+Box2)*Box1 – Box2)/Box1.
# include <iostream.h>
# include <conio.h>
class Box
{
private:
float L,B,H,V;
public:
Box(float Ln,float Bd,float Ht)
{
L=Ln;
B=Bd;
H=Ht;
}
float Volume()
{
V=L*B*H; return V;
}
void operator ++()
{
L=L+2; B=B+2; H=H+2;
}
Box operator +(Box Bx)
{
Bx.L=L+Bx.L; Bx.B=B+Bx.B; Bx.H=H+Bx.H; return Bx;
}
Box operator -(Box Bx)
{
Bx.L=L-Bx.L; Bx.B=B-Bx.B; Bx.H=H-Bx.H; return Bx;
}
Box operator *(Box Bx)
{
Bx.L=L*Bx.L; Bx.B=B*Bx.B; Bx.H=H*Bx.H; return Bx;
}
Box operator /(Box Bx)
{
Bx.L=L/Bx.L; Bx.B=B/Bx.B; Bx.H=H/Bx.H; return Bx;
}
};
void main()
{
clrscr();
float L,B,H;
cout<<"Enter the Length, Breadth and Height of the Box:"; cin>>L>>B>>H;
Box Box1(L,B,H);
cout<<"The cubic volume of Box1 is:"<<Box1.Volume();
++Box1; // The unary operator is overloaded as prefix unary operator on objects
cout<<"\nThe volume of Box1 after 2 units increased is:"<<Box1.Volume();
Box Box2=Box1+Box1;
cout<<"\nThe cubic Volume of Box2 is:"<<Box2.Volume();
Box Box3=((Box1+Box2)*Box1 - Box2)/Box1;
cout<<"\nThe cubic Volume of Box3 is:"<<Box3.Volume();
getch();
}
Output:
Accessing of Private Members by Friend Function and Friend Function Overloading:
If a function is defined as a friend function in C++, then the protected and private data of a class can
be accessed using the function. By using the keyword friend compiler knows the given function is a friend
function. For accessing the data, the declaration of a friend function should be done inside the body of a
class starting with the keyword friend. The function definition does not use either the keyword friend or
scope resolution operator.
Characteristics of a Friend function:
The function is not in the scope of the class to which it has been declared as a friend.
It cannot be called using the object as it is not in the scope of that class.
It can be invoked like a normal function without using the object.
It cannot access the member names directly and has to use an object name and dot membership
operator with the member name.
It can be declared either in the private or the public part.
Advantages of Friend Functions
A friend function is able to access members without the need of inheriting the class.
The friend function acts as a bridge between two classes by accessing their private data.
It can be used to increase the versatility of overloaded operators.
It can be declared either in the public or private or protected part of the class.
Disadvantages of Friend Functions
Friend functions have access to private members of a class from outside the class which violates
the law of data hiding.
Friend functions cannot do any run-time polymorphism in their members.
A friend function can be:
1. A global function
2. A member function of another class
For example: (As global function)
#include <iostream.h>
# include <conio.h>
class ABC;
class XYZ
{
int x;
public:
XYZ(int a)
{
x = a;
}
friend void max(XYZ, ABC);
};
class ABC
{
int y;
public:
ABC(int a)
{
y = a;
}
friend void max(XYZ, ABC);
};
void max(XYZ t1, ABC t2)
{
if (t1.x > t2.y)
cout <<"The member of 1st class is greater:"<< t1.x;
else
cout <<"The member of 2nd class is greater:"<< t2.y;
}
void main()
{
clrscr();
ABC Obj1(20); XYZ Obj2(35); max(Obj2, Obj1);
getch();
}
Output:
The member of 1st class is greater: 35
For Example: (Class Member function as friend function):
#include <iostream.h>
# include <conio.h>
class A; //Foward declaration
class B
{
public:
void Display(A obj);
};
class A
{
private:
int x;
protected:
int y;
public:
A()
{
x = 10;
y = 99;
}
friend void B::Display(A obj);
};
void B::Display(A obj)
{
cout << "Private Variable: " << obj.x;
cout << "\nProtected Variable: " << obj.y;
}
void main()
{
clrscr();
A obj1; B obj2; obj2.Display(obj1); getch();
}
Output:
Private Variable: 10
Protected Variable: 99
Q: WAP to find the area of a square, rectangle, triangle, trapezoid and kite by using the friend function.
# include <iostream.h>
# include <conio.h>
# include <math.h>
class Square
{
private: float Side;
public:
Square(float s)
{
Side=s;
}
friend void Area(Square S);
};
class Rectangle
{
private: float L,B;
public:
Rectangle(float Ln,float Bd)
{
L=Ln; B=Bd;
}
friend void Area(Rectangle R);
};
class Triangle
{
private: float a,b,c,s;
public:
Triangle(float as,float bs,float cs)
{
a=as; b=bs; c=cs;
}
friend void Area(Triangle T);
};
class Trapezoid
{
private: float a,b,h;
public:
Trapezoid(float base1,float base2,float ht)
{
a=base1; b=base2; h=ht;
}
friend void Area(Trapezoid TP);
};
class Kite
{
private: float d1,d2;
public:
Kite(float dg1,float dg2)
{
d1=dg1; d2=dg2;
}
friend void Area(Kite K);
};
void Area(Square S)
{
cout<<"\nThe Area of square is:"<<S.Side*S.Side;
}
void Area(Rectangle R)
{
cout<<"\nThe Area of rectangle is:"<<R.L*R.B;
}
void Area(Triangle T)
{
T.s=(T.a+T.b+T.c)/2;
T.s=(T.s*(T.s-T.a)*(T.s-T.b)*(T.s-T.c));
if(T.s<=0)
cout<<"\nTriangle is not Possible:";
else
cout<<"\nThe Area of Triangle is:"<<sqrt(T.s);
}
void Area(Trapezoid TP)
{
cout<<"\nThe Area of trapezoid is:"<<((TP.a+TP.b)/2)*TP.h;
}
void Area(Kite K)
{
cout<<"\nThe Area of Kite is:"<<(1/2.0)*K.d1*K.d2;
}
void main()
{
clrscr();
float v1,v2,v3;
cout<<"Enter value of one side of a square:"; cin>>v1;
Square Sq(v1);
cout<<"Enter value of length and breadth of a rectangle:"; cin>>v1>>v2;
Rectangle Rt(v1,v2);
cout<<"Enter value of three sides of a Triangle:"; cin>>v1>>v2>>v3;
Triangle Tr(v1,v2,v3);
cout<<"Enter value of opposite bases and height of a Trapezoid:"; cin>>v1>>v2>>v3;
Trapezoid Tp(v1,v2,v3);
cout<<"Enter value of two diagonals of a Kite:"; cin>>v1>>v2;
Kite Kt(v1,v2);
Area(Sq); Area(Rt); Area(Tr); Area(Tp); Area(Kt);
getch();
}
Output:
class B
{
public:
void display(B& Bobj)
{
cout << "The value of Private Variable = " << Bobj.prv << endl;
cout << "The value of Protected Variable = " << Bobj.prt;
}
};
void main()
{
clrscr();
A Aobj; B Bobj; Bobj.display(Aobj);
getch();
}
Output:
The value of Private Variable = 10
The value of Protected Variable = 99
Note: We can declare friend class or function anywhere in the base class body whether its private,
protected or public block. It works all the same.
Q: Using the concept of fried class and friend function WAP to allow the Phone Pay UPI and Paytm UPI to
share the private data of an Account of a person in SBI bank.
# include <iostream.h>
# include <conio.h>
# include <string.h>
# include<iomanip.h>
class SBI
{
private:
char AcNo[21], Name[31],Date[10],DepBy[12],DrawBy[12]; long int Dep,Draw, Balnce;
public:
void Openact()
{
cout<<"Enter the Account No.:"; cin>>AcNo; cin.ignore();
cout<<"Enter the Name:"; cin.getline(Name,31);
cout<<"Enter the Date (DD MM YY):"; cin.getline(Date,10);
cout<<"Enter the Deposit amount:"; cin>>Dep;
Balnce=Dep; strcpy(DepBy,"SBI");
}
char* AccountNo()
{
return AcNo;
}
long int PrevBalance()
{
return Balnce;
}
void Balance()
{
int dd=(Date[0]-48)*10+(Date[1]-48); int mm=(Date[3]-48)*10+(Date[4]-48);
int yy=(Date[6]-48)*10+(Date[7]-48);
cout<<dd<<"-"<<mm<<"-"<<yy<<setw(12)<<AcNo<<setw(14)<<DepBy<<setw(9)<<Dep;
cout<<setw(10)<<DrawBy<<setw(9)<<Draw<<setw(10)<<Balnce<<endl;
}
friend PUpi;
friend PtmUpi;
};
class PUpi
{
public:
SBI Deposit(char Acn[],long int BL,SBI ppobj)
{
cin.ignore(); strcpy(ppobj.AcNo,Acn);
cout<<"Enter the Date (DD MM YY):"; cin.getline(ppobj.Date,12);
cout<<"Enter the Deposit Amount:"; cin>>ppobj.Dep;
ppobj.Balnce=BL+ppobj.Dep; strcpy(ppobj.DepBy,"PhonePay"); strcpy(ppobj.DrawBy," ");
ppobj.Draw=0; return ppobj;
}
SBI Withdrawal(char Acn[],long int BL,SBI ppobj)
{
cin.ignore(); strcpy(ppobj.AcNo,Acn);
cout<<"Enter the Date (DD MM YY):"; cin.getline(ppobj.Date,12);
cout<<"Enter the Withdrawal Amount:"; cin>>ppobj.Draw;
ppobj.Balnce=BL-ppobj.Draw; strcpy(ppobj.DrawBy,"PhonePay"); strcpy(ppobj.DepBy," ");
ppobj.Dep=0; return ppobj;
}
friend SBI Menu(int App,char Acn[],long int BL,SBI MSobj);
};
class PtmUpi
{
public:
SBI Deposit(char Acn[],long int BL,SBI ptobj)
{
cin.ignore(); strcpy(ptobj.AcNo,Acn);
cout<<"Enter the Date (DD MM YY):"; cin.getline(ptobj.Date,12);
cout<<"Enter the Deposit Amount:"; cin>>ptobj.Dep;
ptobj.Balnce=BL+ptobj.Dep; strcpy(ptobj.DepBy,"Paytm"); strcpy(ptobj.DrawBy," ");
ptobj.Draw=0; return ptobj;
}
SBI Withdrawal(char Acn[],long int BL,SBI ptobj)
{
cin.ignore(); strcpy(ptobj.AcNo,Acn);
cout<<"Enter the Date (DD MM YY):"; cin.getline(ptobj.Date,12);
cout<<"Enter the Withdrawal Amount:"; cin>>ptobj.Draw;
ptobj.Balnce=BL-ptobj.Draw; strcpy(ptobj.DrawBy,"Paytm"); strcpy(ptobj.DepBy," ");
ptobj.Dep=0; return ptobj;
}
friend SBI Menu(int App,char Acn[],long int BL,SBI MSobj);
};
SBI Menu(int App,char Acn[],long int BL,SBI MSobj)
{
PUpi Pobj; PtmUpi Ptobj;
int ch;
cout<<"1->Deposit\n2->Withdrawal\nEnter Your Choice:"; cin>>ch;
if(ch==1 && App==1)
{
MSobj=Pobj.Deposit(Acn,BL,MSobj);
return MSobj;
}
else if(ch==2 && App==1)
{
MSobj=Pobj.Withdrawal(Acn,BL,MSobj);
return MSobj;
}
else if(ch==1 && App==2)
{
MSobj=Ptobj.Deposit(Acn,BL,MSobj);
return MSobj;
}
else if(ch==2 && App==2)
{
MSobj=Ptobj.Withdrawal(Acn,BL,MSobj);
return MSobj;
}
else
cout<<"Invalid Choice:"<<endl;
return MSobj;
}
void main()
{
clrscr();
SBI SObj[31];
PUpi PPay;
PtmUpi Ptm;
SObj[0].Openact();
char *Acn=SObj[0].AccountNo();
char Apch='Y';
int D=1,Ap;
while((Apch=='y' || Apch=='Y') && D<=30)
{
long int BL=SObj[D-1].PrevBalance();
cout<<"1->Phonepay\n2->Paytm\nChoose the App:"; cin>>Ap;
if(Ap==1)
{
SObj[D]=Menu(1,Acn,BL,SObj[D]);
D++;
}
else if(Ap==2)
{
SObj[D]=Menu(2,Acn,BL,SObj[D]);
D++;
}
else
{
cout<<"Invalid Choice:";
getch();
clrscr();
}
cin.ignore();
cout<<"\nPress (Y/y) to Continue...:"; cin>>Apch;
}
cout<<"\nTransaction Details are:\n";
cout<<"--------------------------------------------------------------";
cout<<"----------------"<<endl;
cout<<" Date"<<setw(14)<<"A/C No."<<setw(14)<<"Deposited By";
cout<<setw(9)<<"Amount"<<setw(10)<<"Drawn By"<<setw(9)<<"Amount";
cout<<setw(10)<<"Balance"<<endl;
cout<<"--------------------------------------------------------------";
cout<<"----------------"<<endl;
for(int i=0;i<D;i++)
{
SObj[i].Balance();
cout<<"--------------------------------------------------------------";
cout<<"----------------"<<endl;
}
cout<<"\nThank You...";
getch();
}
Output: