Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

C++ Programming Language

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:

i. Sequential Programming Approach


For ex:
void main()
{
int a,b;
printf(“Enter any two Numbers:”);
scanf(“%d %d”,&a,&b);
printf(“The sum is: %d”,a+b);
}

ii. Structural Programming Approach


For Ex:
void main()
{
int n;
printf(“Enter how many nos. do you want:”);
scanf(“%d”,&n);
int x;
for(int i=1;i<=n;i++)
{
printf(“Enter the No. %d:”,i);
scanf(“%d”,&x);
if (x%2==0)
{
printf(“The No. %d is even”,x);
}
else
{
printf(“The No. %d is odd”,x);
}
}
getch();
}

iii. Procedural programming approach (function oriented programming approach):


For Ex: WAP to find the sum of following serieses:
S1=1!+2!+3!+ …+N!
S2=x/1!+x/2!+x/3!+ …. + x/N!
S3=1/1!+2/2!+3/3!+4/4!+….+n/N!
# include <stdio.h>
# include <conio.h>
void main()
{
int N,i;
float s1=0,s2=0,s3=0,x;
float fact(int);
clrscr();
printf("How many terms do you want for series 1:");
scanf("%d",&N);
for(i=1;i<=N;i++)
{
s1=s1+fact(i);
}
printf("How many terms do you want for series 2:");
scanf("%d",&N);
printf("Enter the value of x:");
scanf("%f",&x);
for(i=1;i<=N;i++)
{
s2=s2+x/fact(i);
}
printf("How many terms do you want for series 3:");
scanf("%d",&N);
for(i=1;i<=N;i++)
{
s3=s3+i/fact(i);
}
float s=s1+s2+s3;
printf("The sum of 3 series is:%f",s);
getch();
}
This is the separate program module or a
float fact(int f)
separate procedure or a subroutine program
{
of main routine program implemented as a
float ft=1;
function, thus this approach known as
for(int i=1;i<=f;i++)
procedural approach
{
ft=ft*i;
}
return ft;
}

iv. Object Oriented Programming Approach:


The program designed/written by using the concept of class and object is known as object oriented
programming approach (OOP). In this approach all the logical entities are treated as the objects and an
object can have attributes and behaviors. For similar kind of objects their common attributes and behaviors
are classified by a class. So, a class defines the common attributes and behaviors of similar kind of objects in
form of variables (called as data members) and inform of functions (called as member functions)
respectively.
Hence a class can have two types of members such as Data members and Member functions. For
example: Design a class to find out the area and perimeter of rectangles.
# include <iostream.h>
# include <conio.h>
class Rectangle
{
float l,b,ar,p; Data Members
public:
void input()
{

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();
}

What is Object Oriented Programming?


Object oriented programming means to develop (write) the application programs (software) by using
the concept of class and objects, where the class is a program template or the referential frame of a program
and that program frame can be used by an instance of it, i.e. by a representative of that class. In this way one
create as many No. of instances (called as objects) of a class and each object can use the same program
template of its own independently as two objects are distinct even if they are identical in all respects.
As such it reduces the time and complexity for developing large size programs/software what
happens in traditional monolithic program. It helps for Rapid Application Development (RAD).OOP is a
programming approach for programmers, which helps them how far easily they can handle the coding of a
large size program with code reusability and extendibility facility. OOPS just is an approach but uses all the
programming basics what are required to write the programs. In this approach for every operation the
objects’ behavioral concept is applied in form of coding for program writing, thus the name.
Advantages of Object Oriented Programming
 One of the major advantages of object-oriented programming techniques over procedural programming
techniques is that it reduces the time and complexity for writing a large program where many of codes
and data set are to be used for similar operations by enabling the programmer to create modules that
can be used commonly without doing necessary changes. Also, when a new type of object is added, a
programmer can simply create a new object that inherits many of its features from existing objects. This
makes object-oriented programs easier to modify.
 OOP provides a clear modular structure for programs.
 It is good for defining abstract data types. ( i.e. a class for objects whose behavior is defined by a set of
value and a set of operations.)
 Implementation details are hidden from other modules with clearly defined interface being referenced
by its class.
 It is easy to maintain and modify existing code as new objects can be created from existing ones.
 Objects, methods, instance, message passing, inheritance are some important features found in OOP.
 Encapsulation, polymorphism, abstraction are the fundamentals of such programming language.
 It implements real life scenario.
 In OOP, programmer not only defines data types but also deals with operations applied for data structures.

Write the features/Concepts of Object Oriented Programming (OOP)?


Every object oriented programming language carries the following concepts/features:
Class: In programming context, a class is a user defined data type, which defines the common attributes
and behaviors of similar kind of objects. It defines the common attributes/properties of the objects in
form of variables called data members and common behaviors of the objects in form of functions,
called as member functions or methods. Any instance/representative of a class is known as its object.
Then by using the object, we can use the class members of that object to exhibit an object’s
behaviors. The class code for each object is independent and distinct, that means two identical
objects of same class are distinct. In this way a class provides the code reusability facility i.e. write
the code once and use it as many times do you want with number of instances (i.e. occurrences /
cases). Hence a class is just like a program template/frame from which we can create as many
number of objects and can be called a class is the factory of objects.
Object: It is the instance of a class. It is a self-contained entity consisting of both the data structure and
methods what are defined in its class to exhibit its attributes and behaviors. As such we can say an
object is the physical representative of a class, so that we can do various operations by an object
not by a class. The methods of an object say us what kind of operations we can do through that
object by manipulating its data set. In this way an object can allow us to use/execute the class
programs individually.
(Remember that, we can’t have an object as long as its class is not defined. For defining/creating a class the
following features/concepts are used.)
Abstraction: The process of picking out the common characteristics (data set) and behaviors (Methods) of
similar kind of objects for building their class. It refers to provide only the essential
information to outside world without going in detail implementation. Each abstract member
to outside world is known as its interface. Data abstraction is a programming technique that
relies on the separation of interface and implementation.
(For Ex. While you are operating a TV, you can turn it on or off, you can change the channel, adjust the
volume, etc. of it, but you do not know its detail internal functionality, you are getting only the interfaces not
implementation details.) The abstraction of data members and member functions of class for similar kind of
objects are arbitrary. It depends upon the logic of a programmer as per the application’s demand.
Encapsulation: It is the process of bundling the data and functions required for building the class of similar
kind of objects. So, the wrapping up of data and member functions into a single unit of pack
(called a class) is known as encapsulation. It is one of important feature of OOP, which
makes a class independent from other classes and can be reused without modification in
other program.
Inheritance: It is one of the important features of OOP. It is the mechanism of reusing the data members
and Member functions of an existing class into a new class with or without extendibility code
of the new class.
(Inheritance allows us to define a class in terms of another class, which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality and fast
implementation time. When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the base class/parent class/super class and the new class is known
as the derived class/child class/sub class respectively.)
Polymorphism: Polymorphism is a Greek word, where poly means many and morphic means forms, i.e. many
forms. It is the mechanism of using same method to work differently for different class objects.
It provides the ability of objects of different types to provide a unique interface for different
implementations of methods. It means that on a call to a member function (i.e. method) will
cause a different function (task) to be executed depending on the type of object that invokes
the function. For example, the move() method functions differently for car, chess piece and
window objects.
Other Features:
Information hiding/Data Hiding: Data hiding is a software development technique specifically used in
object-oriented programming (OOP) to hide internal details (data members) of an
object. Data hiding ensures exclusive data access to class members and protects
object integrity by preventing unintended or intended changes. For this it uses some
access specifiers such as private, public and protected. It is done during encapsulation
by keeping the members into these three different sections.
Interface: The abstracted members of a class defined for similar kind of objects to be used in a program are
the interfaces of an object defined in its class. Only the abstracted titles are accessed but the
implementation details are kept hidden.

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;
};

class subclass:public Addition


{
public:
void output()
{
c=10;
d=c*3;
cout<<"\nD="<<d;
}
};
void main()
{
clrscr();
Addition Ad;
Ad.Add();
//Ad.a=10; //Ad.b=20; //Ad.c=Ad.a+Ad.b; // Ad.d=10+15;
cout<<"\nThe addition is:"<<Ad.c;
subclass sb; sb.output(); getch();
}
Q: Find out the area of a Triangle using the OOP concept.
# include <iostream.h>
# include <math.h>
# include <conio.h>
class Triangle
{
private:
float a,b,c,s,Ar;
public:
void Area()
{
cout<<”Enter the value of 3 sides of the Triangle:”; cin>>a>>b>>c;
s=(a+b+c)/2; Ar=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<”The area of the triangle is:”<<Ar;
}
};
void main()
{
clrscr();
Triangle T;
T.Area();
getch();
}
Q: Design the class to calculate the bill amount of electricity you consumed, where Rs. 3 is charged for
each unit. Then execute this class program to show the amount.
# include <iostream.h>
# include <conio.h>
class Ebills
{
private:
float units, Bamt;
public:
void Billamt()
{
cout<<”Enter the No. of units consumed:”;
cin>>units;
Bamt=units*3;
cout<<”The bill amount is:”<<Bamt;
}
};
void main()
{
clrscr();
Ebills eobj;
eobj.Billamt();
getch();
}

Difference Between Structure and Class


Features Structure Class
Definition A structure is a group of variables of In C++, a class is defined as a collection of related
various data types referenced by the variables and functions contained within a single
same name. structure.
Basic If no access specifier is specified, all If no access specifier is defined, all members are
members are set to 'public' by default set to 'private' by default
Declaration struct structure_name{ class class_name{
type member1; data members;
type member2; member functions;
………. };
type memberN;
};
Instance Structure instance is called the A class instance is called 'object'.
'structure variable'.
Inheritance It does not support inheritance. It supports inheritance.
Memory Memory is allocated on the stack. Memory is allocated on the heap.
Allocated
Nature Value Type Reference Type
Purpose Grouping of data Grouping both the data and functions
Null values Not possible It may have null values.
Requires It does not support constructor and It may have all the types of constructors and
constructor and destructor member functions. destructors.
destructor

Types Statements in C++:


Like ‘C’ language, C++ can have two types of statements: Simple statements and compound
statement. Ex. cout<<”Hello World”; (This is a simple statement, it is single line and ended with semicolon)
if(N%2==0)
Here if…else statement is a compound statement, this type of statements
{
don’t ended with semicolon and takes a block of simple statements under it.
cout<<”It is even”;
}
else
{
cout<<”It is Odd”;
}

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 Word Identifier Operator Literal/Constant Separator

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;
}

I/O operations in C++:


In C++, the I/O operation is done by using the stream concept. Stream is the sequence of bytes or
flow of data. It makes the performance fast. If bytes flow from main memory to device like printer, display
screen, or a network connection, etc. this is called as output operation. If bytes flow from device like Key
Board, Mouse, Scanners or a network connection, etc. to main memory, this is called as input operation.
I/O Library Header Files:
The common header files used in C++ programming are:
Header File Function and Description
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output stream,
standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision and
setw.
<fstream> It is used to declare services for user-controlled file processing.
The cout is a predefined object of ostream class. It is connected with the standard output device,
which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to
display the output on a console.
The cin is a predefined object of istream class. It is connected with the standard input device, which
is usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to read the input
from a console.
The endl is a predefined object of ostream class. It is used to insert a new line characters and
flushes the stream.
cin is an object of the input stream and is used to take input from input streams like files, console,
etc. cout is an object of the output stream that is used to show output. Basically, cin is an input statement
while cout is an output statement.
They also use different operators. cin uses the extraction operator( >> ) while cout uses the
insertion operator( << ).
For example, if you want to read an int value in a variable myint(using cin) and then print it to the
screen(using cout), you'd write:
Example
#include<iostream.h>
int main()
{
int myint;
cout<<”Enter an integer:”<<endl;
cin >> myint;
cout << myint;
return 0; }
<iomanip.h> header file:
iomanip is a library that is used to manipulate the output of C++ program. The header <iomanip.h>
consists of functions that are used to manipulate the output of the C++ program. We can make the output
of any program neater and presentable based on where we want to show it or who is going to use it. To
format the output properly, we can use the manipulators provided by the <iomanip> header and make the
output presentable.
For Example, if we are printing the elements of a matrix as follows:

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:

Note: There is no effect of setprecision() on integer values.


setw: Setw function sets the field width or number of characters that are to be displayed before a particular
field.
Example:
#include <iostream.h>
#include <iomanip.h>
void main ()
{
cout << "The number printed with width 10"<<endl;
cout << setw(10); cout << 77 << endl;
cout << "The number printed with width 2"<<endl;
cout << setw(2);
cout << 10 << endl;
cout << "The number printed with width 5"<<endl;
cout << setw(5);
cout << 25 << endl;
}
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();
}

Member Functions of Classes:


A function declared as a member (without the friend specifier) of a class is called as member
function. Member functions are mostly specified with public specifier because they have to be called
outside of the class as the object’s interface. A member function can be called / invoked either in a program
or in another function of the same class. The member functions of a class can be implemented as per their
nature as follows:
i. Manager Functions
ii. Accessor Functions
iii. Implementer functions
Manager Functions: These are used to perform initialization and cleaned up (de-initialization) of the
instance of the class objects. For Ex. Constructors and Destructors.
# include <iostream.h>
# include <conio.h>
class Rectangle
{
//int x=10,y=20; // Here, you can’t directly initialize the data member like this in C++
int x,y;
public:
void Disp()
{
cout<<"x="<<x<<" and " <<"y="<<y;
}
};
void main()
{
clrscr();
Rectangle R;
R.Disp(); //This function displayed garbage value of x and y data member of R object as 0 and 7671
getch(); //Because as long as the data member of an object is not initialized, it will show the garbage
}
Constructor as Manager Function:
# include <iostream.h>
# include <conio.h>
class Rectangle
{
int x,y;
public:
Rectangle(int a,int b) //Here the constructor Rectangle() playing the role of a Manager function
{x=a;y=b;}
void Disp()
{
cout<<"x="<<x<<" and " <<"y="<<y;
}
};
void main()
{
clrscr();
Rectangle R(10,20);
R.Disp();
getch();
}
Output:

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:

Types of member functions of a class:


i. Constructors
ii. Destructors
iii. Normal / Simple member functions
iv. Inline Member functions
v. Static member functions
vi. Constant member functions
vii. Friend member functions
viii. Virtual member functions
ix. Operator overloading member functions
x. Conversion function
Defining the Member function of a class:
A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. It operates on any object of the class of which it is a member, and has
access to all the members of a class for that object.
Member functions can be defined within the class definition or separately using scope resolution
operator (::). Defining a member function within the class definition declares the function inline, even if
you do not use the inline specifier. So either you can define Volume() function as below:
class Box
{
private:
double length;
double breadth;
double height;
public:
double getVolume()
{
return length * breadth * height;
}
};
Or you can define Volume() function as below:
class Box
{
private:
double length;
double breadth;
double height;
public:
double getVolume();
};

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);
};

void Box::setHeight( double ht )


{
height = ht;
}

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;

cout<<”Enter the length, breadth and height of the box2:”;


cin>>L>>B>>H;
Box2.setLength(L);
Box2.setBreadth(B);
Box2.setHeight(H);
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
getch();
}

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.

Normal Function Calling Inline Function calling


Remember, inlining is only a request to the compiler, not a command. The compiler can ignore the
request for inlining.
The compiler may not perform inlining in following cases:
1. If a function contains a loop. (for, while and do-while)
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement doesn’t exist in a function body.
5. If a function contains a switch or goto statement.

Why Inline Functions are used?


When the program executes the function call instruction the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack, and finally
transfers control to the specified function. The CPU then executes the function code, stores the function
return value in a predefined memory location/register, and returns control to the calling function. This
can become overhead if the execution time of the function is less than the switching time from the caller
function to called function (callee).
However, for small, commonly-used functions, the time needed to make the function call is often a lot
more than the time needed to actually execute the function’s code. This overhead occurs for small
functions because the execution time of a small function is less than the switching time. That’s why we
use the inline function.
Defining inline function:
It is also possible to define the inline function inside the class. In fact, all the functions defined
inside the class are implicitly inline. Thus, all the restrictions of inline functions are also app lied here. If
you need to explicitly declare an inline function in the class then just declare the function inside the class
and define it outside the class using the inline keyword.
Syntax:
class S
{
public:
inline int square(int s) // redundant use of inline
{
// this function is automatically inline
// function body
}
};
For example:
#include <iostream.h>
# include<conio.h>
class operation
{
int a, b, add, sub, mul;
float div;
public:
inline void get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
}
inline void sum()
{
add = a + b;
cout << "Addition of two numbers: " << a + b << "\n";
}
void difference();
void product();
void division();
};

inline void operation ::difference()


{
sub = a - b;
cout << "Difference of two numbers: " << a - b << "\n";
}
inline void operation ::product()
{
mul = a * b;
cout << "Product of two numbers: " << a * b << "\n";
}
inline void operation ::division()
{
div = a / b; cout << "Division of two numbers: " << a / b << "\n";
}
void main()
{
clrscr();
cout << "Program using inline function\n";
operation s;
s.get();
s.sum(); s.difference(); s.product(); s.division();
getch();
}

Simple Member functions in C++:


These are the basic member functions, which don’t have any special keyword like static, friend,
inline, virtual etc. as prefix. All the general member functions which are having only the return type and/or
arguments are termed as simple or basic member functions. For example:
Q: Calculate the water bill amount of a consumer on the basis of condition that the first 500 ltr. Rs. 2/- is
charged, for next 300 ltr. Rs. 3/- is charged and for next 200 ltr. Rs. 4/- is charged and after 1000 ltr. Rs.
5/- is charged per liter. Then calculate and display the Water Bill Amount to pay with consumer number.
# include <iostream.h>
# include <conio.h>
class WaterBill
{
float Units,Billamount;
char *CNo;
public:
void getUnits()
{
cout<<"Enter the Consumer Number:";
cin>>CNo;
cout<<"Enter how many liters of water consumed:";
cin>>Units;
}
void Calculate();
};

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:

C++ Overloading Operation:


If we create two or more members having the same name but different in number or type of
parameter, it is known as C++ overloading. We can have two types of overloading in C++ such as: Function
Overloading and Operator Overloading.
Function Overloading:
Function Overloading is defined as the process of having two or more function with the same name,
but different in parameters is known as function overloading in C++. In function overloading, the function is
redefined by using either different types of arguments or a different number of arguments. It is only
through these differences compiler can differentiate between the functions. Function overloading can be
considered as an example of a polymorphism feature in C++.
The advantage of Function overloading is that it increases the readability of the program because
you don't need to use different names for the same action.
For example, Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the function such as Add1(int,int) for two parameters, and
Add2(int,int,int) for three parameters then it may be difficult for you to understand the behavior of the
function because its name differs.
Overloading Considerations
Function declaration element Used for overloading?
Function return type No
Number of arguments Yes
Type of arguments Yes
Presence or absence of ellipsis Yes
Use of typedef names No
Unspecified array bounds No
const or volatile Yes, when applied to entire function
Reference qualifiers (& and &&) Yes

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:

Accessing of Private Members by Friend Class:


A friend class can access private and protected members of other classes in which it is
declared as a friend. It is sometimes useful to allow a particular class to access private
and protected members of other classes. For example, a LinkedList class may be allowed
to access private members of Node. We can declare a friend class in C++ by using
the friend keyword. For Example:
#include <iostream.h>
# include <conio.h>
class A
{
private:
int prv;
protected:
int prt;
public:
A ()
{
prv = 10;
prt = 99;
}
friend class B;
};

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:

You might also like