0% found this document useful (0 votes)
4 views

03 Classes & Obj 20-21-Converted

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, focusing on classes, objects, member functions, and access specifiers. It explains the syntax for defining classes and creating objects, as well as the differences between inline and non-inline functions, and various parameter passing techniques. Additionally, it covers the visibility modes (public, private, protected) and how to handle function parameters and return types in relation to objects.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

03 Classes & Obj 20-21-Converted

The document provides an overview of Object-Oriented Programming (OOP) concepts in C++, focusing on classes, objects, member functions, and access specifiers. It explains the syntax for defining classes and creating objects, as well as the differences between inline and non-inline functions, and various parameter passing techniques. Additionally, it covers the visibility modes (public, private, protected) and how to handle function parameters and return types in relation to objects.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

B.Sc.

II (Sem-iii) Year: 2020 OOPS lalita bhosale

Classes and Objects

Class
Class is user defined data type which is collection of data member and member functions.
Class can be declared or defined by using keyword ‘class’ followed by ‘class_name’ which is an
identifier.
Syntax to declared or defined class:
class class_name
{
data_type datamem1;
Data members
data_type datamem2;

data_type datamemN;

return_type mem_fun1( );
return_type mem_fun2( ); Member functions

return_type mem_funN( );
};

• By default all the data of class are private therefore this data cannot be accessed outside
the world.
• Multiple objects can be created for the single class whenever required and each object
hold individual record.
• A class provides the blueprints for objects.
• When you define a class, you define a blueprint for an object. That is what an object of
the class will consist of and what operations can be performed on such an object.

e.g. Following example shows the definition of employee class:

class emp
{
int emp_no;
char name[20], add[20]; Data members (Attributes)
float salary;

void get( ); Member functions (Operations)


void show( );
};

Object:
• An Object is an instance or variable of class.
• An object can be thought of as an entity which can represent person, place, animal etc.
• Object is such run time entity which holds entire data and functions of class.
• When program is executed, the objects interact with each other by sending messages to
one another. That is due to object message passing is also done.
• There are three properties related with objects:
o Identity: This property of an object that distinguishes it from other objects
o State: This property describes the data stored in the object
o Behavior: This property describes the methods in the object's interface by which
the object can be used
• Multiple objects can be created for the single class whenever required and each object
hold individual record.
Syntax to create object: Class_name object; OR class Class_name object;
Here, class_name is name of the class which is an identifier.
‘Object’ is name of object which is also an identifier.
e.g. For above class ‘emp’ we can create object as follows:

1
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

emp x,y,z;
Here, x, y and z are objects of class ‘emp’

Scope resolution operator:


We know that, every programming language having their rich set of operators. And
every operator performs their own task. Like that, C++ language has one special operator
called scope resolution operator, which is used to access global declared data.
Symbol of Scope resolution operator:
::
Syntax to use scope resolution operator:
:: global_data;
Here, ‘global_data’ may be global variable or function etc.
Working of Scope resolution operator:
This operator used to access global declared data.
Following program demonstrates the use of scope resolution operator:

# include<iostream.h>
#include<conio.h>
int x =10;
void main( )
{
int x=50;
clrscr( );
cout<<“Local value=”<<x;
cout<<“\nGlobal value=”<<::x;
getch( );
}

Output:
Local value= 50
Global value= 10

➢ Member functions:
The functions which are declared or defined under class body and which are called with
the help of object of class only such functions are called as ‘Member functions’.

➢ Non Member functions:


The functions which are not declared or defined under class body and which are not
called with the help of object of class such functions are called as ‘Non member
functions’.

*Defining member functions of class:


We can define member functions of class by two ways:
1) Inside class body
2) Outside class body
Let us see in details:
1) Defining member functions inside class body:
We can define member functions of class inside class body as follows:
Syntax:
class class_name
{
return_type func1_name(datatype arg1,datatype arg2, ...... )
{
Body of function;
}
return_type func2_name(datatype arg1,datatype arg2, ...... )
{
Body of function;
}
};

Following example shows defining member functions inside class body:

2
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

class add
{
int a,b,c;
void get( )
{
cout<< “Enter any two no:”;
cin>>a>>b;
}
void show( )
{
c = a + b;
cout<< “Addition= ”<<c;
}
};
Note that:
Whenever we define functions inside class body then by default compiler treats that
functions as inline function.

2) Defining member functions outside class body:


We can define member functions of class outside class body also which is as follows:
Syntax:
return_type class_name :: funct_name(datatype arg1,datatype arg2, ...... )
{

Body of function;

Following example shows defining member functions outside class body:

class add
{
int a,b,c;
void get( );
void show( )

};
void add::get( )
{
cout<< “Enter any two no:”;
cin>>a>>b;
}
void add::show( )
{
c = a + b;
cout<< “Addition= ”<<c;
}

Note that:
Whenever we define functions outside class body then compiler does not treats that
functions as inline function and this is major difference between defining functions inside class
body and outside class body.

Inline Function:
• Definition: “The functions having easy and small coding and which are not pushed into
systems stack by the compiler while its calling such functions are called as inline
functions.”
• We know that function calling is one of the most important things in execution of
function body.
• About non-inline functions, whenever function call is made then compiler push that
function in systems stack and then its execution is happen.
But, inline function is such function that does not push into systems stack by
the compiler i.e. inline function calling is replaced by its definition therefore
execution of inline function becomes fast (Due to avoidance of push into stack)
• Characteristics of Inline function:
o Inline functions having easy & small coding.
o An Inline function does not contains any looping statement, switch statement,
static variables.

3
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

o Inline functions are not recursive.


o It does not require function calling overhead.
o Inline functions works as macro in C++ language.

Note that:
We know that, when we define functions inside class body then by default compiler treats
that functions as inline function. And hence its definition should be easy & small with no use of
looping, switch statements, static variable etc.
* If forcefully programmer defines its body with looping, switch statements or static variable etc.
then compiler executes that defined functions as normal functions and push it into systems stack
for execution.

Making outside class defined Function as inline:


We also make class outside defined function as inline. To make outside defined functions as
inline, we just have to use ‘inline’ keyword before its definition.
Syntax:

inline return_type class_name :: funct_name(datatype arg1,datatype arg2, ...... )


{

Body of function;

E.g. Following example shows making outside defined functions as inline:

class add
{
int a,b,c;
void get( );
void show( )

};
inline void add::get( )
{
cout<< “Enter any two no:”;
cin>>a>>b;
}
inline void add::show( )
{
c = a+ b;
cout<< “\n Addition= “<<c;
}

Visibility modes( Access Specifiers) in C++:


The access specifiers are used to give security for the data. i.e. to give accessibility of members
of class.
In C++ language, there are three kinds of access specifers viz:
1) Public
2) Private
3) Protected
Following tables shows access specifiers with their accessibility or visibility:
Access specifier Accessed by Not Accessed by
All functions i.e.
o Member functions
Public o non member functions
o friend functions
o derived class functions
o Member functions o Non member function
Private o Friend function (except friend function)
o Derived class functions
o Member functions o Non member function
Protected o Friend function (except friend function)
o Derived class functions
Let us see all these accessibility in details:
1) Public:
Public data can easily accessed by any function i.e. they are accessed by member
functions, non member functions, friend functions and also derived class
functions. This type of data is not secured and hence it is easily accessed.
4
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

2) Private:
Private data accessed by member functions and friend functions only.
Private data is not accessed by non member functions (except friend function)
and derived class functions.
3) Protected:
Protected data accessed by member functions, friend functions and also derived
class functions.
Protected data is not accessed by non member functions (except friend function).
Note that:
A Friend function is such a non member function that can access all data i.e. public,
private and protected data easily.

Reference Variable:
We know that, there are three kinds of variable present in C++ language.
1) Value variable:
➢ This type of variable is used to store only value.
➢ It is easy to use but it is less powerful than pointer variable.
➢ Only copy of value of one variable can be assigned to another variable.
➢ Therefore making operation on such variable does not affects on value of
existing variable.
e.g.
int x,y;
x = 10 ;
y = x;
y = 100;
cout<< x;
output:
10

2) Pointer variable:
➢ This type of variable is used to store address of another variable.
➢ It is hard to use (because we use * or & operator along with pointer variable)
but it is powerful than value variable.
➢ It holds address of variable in it.
➢ Therefore making operation on such variable affects on value of existing
variable.
e.g.
int x =10, *y;
y = &x;
*y = 100;
cout<< x;
output:
100
3) Reference variable: (Alias)
➢ This type of variable is used to give alternative name (alias) for existing
variable.
➢ It is easy to use same as value variable and has power of pointer variable.
➢ Therefore making operation on such variable affects on value of existing
variable also.
➢ Syntax for reference variable:

Datatype &ref_var_name= existing variable;


e.g.
int x =10,
int &y= x; // here ‘y’ is reference variable.
y = 100;
cout<< x;
output:
100
Parameter passing techniques:
C++ language supports three kinds of parameter passing techniques;
1) Pass by Value (Call by value)
2) Pass by Pointer (Call by pointer) or Pass by address
3) Pass by reference.
Let us see all these techniques in details:

5
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

1) Pass by Value (Call by value):


o Passing value of variable to called function is called as “Pass by value” or “call by
value”
o In this case only value of actual parameter is copied into formal parameter
therefore making some operations on formal parameter does not affect on value
of actual parameter.
o Syntax for calling:
Funct_name(variable_name);
2) Pass by Pointer (Call by pointer/Address):
o Passing address of variable to called function is called as “Pass by
pointer/address” or “call by pointer/address”
o In this case address of actual parameter is copied into formal parameter
therefore making some operations on formal parameter affects on value of actual
parameter.
o Syntax for calling:
Funct_name(&variable_name);
OR
Funct_name(pointer);
3) Pass by Reference (Call by reference):
o Passing reference variable (alias) of existing variable to called function is called as
“Pass by reference” or “call by reference”
o In this case alias of actual parameter is copied into formal parameter therefore
making some operations on formal parameter affects on value of actual
parameter.
o Syntax for calling:
Funct_name(Reference_var_name);
OR
Funct_name(variable_name);
Following program shows the concept of parameter passing techniques in C++:
#include<iostream.h>
#include<conio.h>
class pass
{
public:
void call_val(int);
void call_ptr(int*);
void call_ref(int&);
};
void pass::call_val(int a)
{
a = 100;
}
void pass::call_ptr(int *b)
{
*b = 400;
}
void pass::call_ref(int &c)
{
c = 700;
}
void main( )
{
pass n;
int x,*y;
int &z=x; //’z’ is reference variable
y = &x; //initialization of pointer
clrscr( );
x = 50;
n.call_val(x); //call by value
cout<< “\n After call by value=”<< x;
n.call_ptr(y); //call by pointer
cout<< “\n After call by Pointer=”<< x;
n.call_ref(z); //call by reference
cout<< “\n After call by Reference=”<< x;
getch( );
}
OUT PUT: After call by value= 50
After call by Pointer= 400
After call by Reference= 700

6
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

Function returning and accepting object as parameter:


Function accepting object:
Like normal parameter we can also pass object as parameter to the function.
To pass object to function then it is declared as:
Return_type funct_name(Class_Name);
Here,
‘Return_type’ is any valid data type that suggests value return from function.
‘funct_ name’ is name of function which is an identifier.
‘Class_name’ is name of the class due to this complier known that declared
function accept object of that class.
E.g. Suppose, there is ‘emp’ class and get( ) function declared as follow.
void get(emp);
In above declaration, ‘get’ function accept object of ‘emp’ class.
Function returning object:
Like normal way we can also return object of class from the function.
To return object from function then it is declared as:
Class_name funct_name(Argument list);
Here,
‘Class_name’ is return type of function there for compiler known that
declared function returns object of class
funct_ name is name of function which is an identifier.
‘Argument list’ is value accept by the function.
E.g. Suppose, there is ‘emp’ class and get( ) function declared as follow.
emp get( );
In above declaration, ‘get’ function returns object of class.
// Function accepting and returning object of class
#include<iostream.h>
#include<conio.h>
class emp
{
int empno;
char empname[20];
float sal;
public:
void show(emp);
emp get( );
};
emp emp::get( ) //returns object of 'emp' class
{
emp p;
cout<<"\n Enter EMp no ";
cin>>p.empno;
cout<<"\n Enter emp Name ";
cin>>p.empname;
cout<<"\n Enter emp sal ";
cin>>p.sal;
return(p);
}
void emp:: show(emp a) //accept object of 'emp' class
{
cout<<"\n Emp No= "<<a.empno;
cout<<"\n Emp Name= "<<a.empname;
cout<<"\n Emp Sal= "<<a.sal;
}
void main()
{
emp x,z;
clrscr();
x=z.get( );
z.show(x);
getch( );
}

7
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

Array of Object:
• We know that class variable (Object) can hold only one record at a time.
• We know that to store multiple values in single variable, we create array.
• As like normal array, we also able to create arrays of class variable (Arrays of Object) to
store multiple records at a time.
Syntax to Create Arrays object:

class tag_name array_Name[size1][size2]………[sizeN];


OR
tag_name array_Name[size1][size2]………[sizeN];

here;
‘class’ is keyword
‘tag_name’ is class name which is an identifier
‘array_Name’ is name of array’s of object which is an identifier
size1, size2,………, sizeN are integer values which shows number of records stored in
arrays of class.
Following program shows the concept of arrays of object to accept and display two cricketer
records:

# include < iostream.h >


# include < conio.h >
class cricket
{
int pno;
char name[20];
float bat_avg , ball_avg;
public:
void get( );
void show( );
};
void cricket::get( )
{
cout<< “Enter player no:”;
cin>>pno;
cout<< “\nEnter player name:”;
cin>>name;
cout<< “\nEnter player Bat AVG:”;
cin>>bat_avg;
cout<< “\nEnter player Ball AVG:”;
cin>>ball_avg;
}

void cricket::show( )
{
cout<< “\nPlayer no:”<<pno;
cout<< “\nPlayer name:”<<name;
cout<< “\nPlayer Bat AVG:”<<bat_avg;
cout<< “\nPlayer Ball AVG:”<<ball_avg;
}

void main( )
{
cricket x[2]; // arrays of object
int i;
clrscr( );
for( i= 0 ; i<=1 ; i++)
{
x[i].get( );
}

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


{
x[i].show( );
}
getch( );
}

8
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

In above example two cricketer records are accepted from user and displayed the
accepted records.
Both records are stored in array x at individual index i.e. first record is stored at index 0 and
second record is stored at index 1 following manner:
pno = 54
x[0] name = Rahul
bat_avg = 45.63
ball_avg = 15.36

pno = 99
x[1] name = Sachin
bat_avg = 54.63
ball_avg = 25.36

Also we can access individual elements from above array of object as fallow:
x[0].bat_avg will access 45.63
x[0].ball_avg will access 15.36
x[1].name will access Sachin
x[1].bat_avg will access 54.63

Pointer To Class Variable (Pointer to object):


• We know that pointer is a variable which stores address of another variable in memory.
As like normal variable pointer, we are also able to create the pointer to class variable
(pointer to object) which can holds the address of another object.
Syntax to declare pointer for structure variable:
class tag_name * pointerName;
OR
tag_name * pointerName;
Here,
‘class’ is keyword
‘tag_name’ is class name
pointerName is Identifier

Note:
To access the data member of structure by using its pointer, the
arrow (→ ) operator is used instead of dot ( . ) operator along with pointer object.
Following program shows the concept of pointer to object:

# include < iostream.h > void book::get( )


# include < conio.h > {
class book cout<< “\nBook no=”<<bno;
{ cout<< “\nBook name=”<<bname;
int bno; cout<< “\nBook price=”<<price;
char name[20]; }
float price; void main( )
public: {
void get(); clrscr( );
void show(); book *p; //pointer to object
}; book q;
void book::get( ) p= &q; // initialization of pointer
{ p→get();
cout<< “\nEnter book no:”; p→show();
cin>>bno; getch();
cout<< “\nEnter book name:”; }
cin>>bname;
cout<< “\nEnter book price”;
cin>>price;
}

9
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

Nested Class :
• If we define or declare one class inside another class then such a form is called as
“class within class or Nested class”
• Using this facility complex data type can be created.
• Nested class is used to access elements of class which is part of another class.
Syntax for nested class:
class outerclass_name
{
-
-
-
class innerclass_name
{

};
};

Syntax to define inner class member functions:


Return_type outerclass_name::innerclass_name::funct_name(datatype arg1,........ )
{

}
Syntax to create object of inner class:
outerclass_name::innerclass_name object;

Following program demonstrate the concept of nested classes:


#include<iostream.h>
#include<conio.h> void college::student::sget( )
class college {
{ cout<<"\n Enter Roll no: ";
int cno; cin>>roll;
char cname[20]; cout<<"\n Enter name: ";
public: cin>>name;
void cget(); cout<<"\n Enter Per: ";
void cshow(); cin>>per;
class student }
{
int roll; void college::student::sshow( )
char name[20]; {
float per; cout<<"\n Roll no: "<<roll;
public: cout<<"\n Name: "<<name;
void sget( ); cout<<"\n Per: "<<per;
void sshow( ); }
}; void main( )
}; {
void college::cget( ) clrscr( );
{ college x;
cout<<"\n Enter college no: "; college::student y;
cin>>cno; x.cget( );
cout<<"\n Enter college Name: "; x.cshow( );
cin>>cname; y.sget( );
} y.sshow( );
void college::cshow( ) getch( );
{ }
cout<<"\n College NO= "<<cno;
cout<<"\n College Name= "<<cname;
}

10
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

Default Argument:
❖ We know that, in ‘C’ language to call the function we need to pass every argument.
❖ While calling function, if we don’t pass argument then ‘C’ function can’t be invoked.
❖ But, C++ language supports such a concept of default argument which assigns default
value for the formal parameter of called function if no value passed while calling.
❖ C++ compiler assigns default value to the formal parameter if no parameter passed to
function while calling.
❖ Syntax to declare a function with default argument:

Return_type funct_name(datatype=defaulvalue,datatype=defaultvalue, . ….);

E.g.
void accept(int=40,char[ ]= “Mumbai”);
In above, function declaration accept() function declared with two default values 40 and
“Mumbai”.
While calling accept( ) function, if we don’t pass arguments then default values i.e 40 and
“Mumbai” is automatically assigns to corresponding formal parameters by C++ compiler.
Following program shows the use of default argument concept:

#include<iostream.h>
#include<conio.h>
class concept
{
public:
void get(int=10,char[ ]="Mumbai"); // funct. With default arg

};
void concept::get(int x, char y[ ])
{
cout<<"\n Value= "<<x;
cout<<"\n Name= "<<y;
}
void main()
{
clrscr( );
concept a,b;
a.get( ); //function called without arg.
b.get(50); // function called with one arg.
getch( );
}

OUTPUT:
Value=10
Name= Mumbai
Value=50
Name= Mumbai

Memory Allocation:
Allocation of memory space for particular data is called as “Memory allocation”
Memory allocation is done at two times viz:
1) Compile time memory allocation (Static memory allocation)
2) Runtime memory allocation (Dynamic memory allocation)
Let us see all this in briefly….
1) Compile time memory allocation (Static memory allocation):
Allocation of memory space for particular data at compile time of program is called as
“Compile time” or “Static” memory allocation.
Disadvantages of Compile time memory allocation:
1) In compile time memory allocation there is memory wastage problem.
E.g.
Consider, we declare one array as int x[50];
➢ In above declaration, compiler allocates 100 bytes of memory for 50 integers
of ‘x’ array at compile time.
➢ But, actually at runtime of program we accept and store only 10 integers in
array ‘x’ therefore only 20 bytes of memory we used at runtime.
➢ Thus, at compile time 100 bytes of memory are reserved but at runtime we
use only 20 bytes. What about remaining 80 bytes? i.e. it is wastage.
2) Due to compile time memory allocation for array, we maximum stores elements
equal to the size of array. That is size of array cannot grow at runtime.
11
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

To overcome the drawback of static memory allocation, the concept of dynamic memory
allocation is introduced.
2) Runtime memory allocation (Dynamic memory allocation):
Allocation of memory space for particular data at run time of program is called as
“Runtime” or “Dynamic” memory allocation.
Advantages of Runtime memory allocation:
1) In runtime memory allocation there is no memory wastage problem. This is due
to memory is allocated at runtime.
2) At runtime of program we stores lots of elements in variable because there no fix
size of variable like array.
In C++ language, there are two operators which participated in dynamic memory allocations.
Memory Management operators in C++:
1) ‘new’ operator
2) ‘delete’ operator
Let us see all this in briefly….
1) ‘new’ operator:
➢ ‘new’ operator is unary operator i.e. it operates on only one operand.
➢ ‘new’ operator is used to allocate memory space for particular data at runtime of program.
➢ Syntax for ‘new’ operator:

Pointer = new datatype[size];

Here, ‘Pointer’ is pointer variable


‘new’ is keyword i.e. it is operator
‘datatype’ is any valid data type in C++
‘size’ is integer value.
e.g.
int *x;
x = new int[20];
In above declaration, dynamically memory is allocated for 20 integers. This is
due to ‘new’ operator.
1) ‘delete’ operator:
➢ ‘delete’ operator is also unary operator i.e. it operates on only one operand.
➢ ‘delete’ operator is used to de-allocate or free or release the previously allocated runtime
memory for future use.
➢ Syntax for ‘delete’ operator:

delete pointer;

Here, ‘Pointer’ is pointer variable


‘delete’ is keyword i.e. it is operator used to release the memory
e.g.
int *x;
x = new int[20]; // runtime memory allocation for 20 integers
delete x; // release the allocated memory.
Following program shows use of ‘new’ and ‘delete’ operators:
#include<iostream.h> void concept::show( )
#include<conio.h> {
class concept cout<< “\nYour numbers=”;
{ for(i=0;i<=n-1;i++)
int *p, i, n ; {
public: cout<<“\t”<<p[i];
void get( ); }
void show( ); delete p; // release the memory
}; }
void concept::get( )
{ void main( )
cout<< “\nHow many numbers? ”; {
cin>>n; concept m;
p = new int[n]; //allocates memory for ‘n’ integers m.get( );
cout<< “\n Enter these elements=”; m.show( );
for(i=0;i<=n-1;i++) getch( );
{ }
cin>>p[i];
}
}

12
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

Function overloading:

➢ In C++ language we are able to take or define many functions having same name but
all these functions are differ from each other according to signatures (type of argument
and number of argument accept by function) such concept is called as “Function
Overloading”
➢ “Overloading” means one name having multiple meaning i.e. a function having distinct
multiple meaning.
➢ Function overloading is type of “Compile time polymorphism” i.e. all the overloaded
functions are get selected by the compiler at compile time of program.
➢ At compile time, compiler selects such functions according to their type and number of
arguments.
➢ Consider following function prototype:
void add();
void add(int);
int add(int,int);
In above declaration, add( ) function is overloaded three times and all these functions
are differ from each other according their signatures.

Advantages of Function overloading:


1) All function names are same therefore it is easy to maintain the code.
2) Programming code becomes clean and easy to debug.
3) It eliminates the use of different function names for the same operations.
4) Function calls are faster because all the information to call the function is available
at compile time of program.

Following program demonstrate the concept of function overloading:

#include<iostream.h>
#include<conio.h> void over::show( )
class over {
{ cout<<"\n Result= "<<c;
int a,b,c; }
public: void main( )
void add(); {
void add(int); clrscr( );
void add(int,int); over z;
void show(); z.add( );
}; z.show( );
void over::add( ) z.add(50);
{ z.show( );
cout<<"\n Enter two no: "; z.add(40,60);
cin>>a>>b; z.show( );
c=a+b; getch( );
} }
void over::add(int x)
{ OUT PUT:
cout<<"\nEnter one no: "; Enter two no: 70 80
cin>>b; Result= 150
c=x+b; Enter one no: 40
} Result= 90
void over::add(int x,int y) Result= 100
{
c=x+y;
}

13
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

➢ Friend function:
• We know that by default all the data of class is private therefore such type of data is not
accessed by non-member function.
• But in some situation we have to access such private data inside non member function.
For that purpose friend functions are used.
• Definition: “The non member function that has ability to access all kind of data (public,
private and protected) of class such function is called as ‘Friend function’
• Characteristic of friend function:
1) The scope of friend function is unlimited i.e. we can declare it in any section
(public or private or protected) of class.
2) In side friend function, data of class only accessed by using object of class.
3) Generally, friend function accept object of class as argument.
4) Friend function cannot define inside class body. Because it is non-member
function.
5) Friend functions are defined outside the class body like normal function i.e.
there is no need of class name or scope resolution operator (::) etc.
6) Friend functions are not accessed or called with the help of object of class
because it is non member function.
7) Friend functions are not considered class members; they are normal external
functions that are given special access privileges of class.
8) ‘friend’ keyword is used to declare a function as friend.
• Syntax to declare friend function:

friend return_type fun_name(argument list);

Here,
‘friend’ is keyword that tells compiler the declared function is friend.
‘return_type’ is any valid data type in C++ that shows value return from function.
‘fun_name’ is name of friend function.

Following program demonstrate the use of friend function:


#include<iostream.h>
#include<conio.h>
class emp
{
int empno;
char name[20];
float sal;
friend void show(emp); //friend fun. declaration
public:
void get( );
};
void emp::get( )
{
cout<<"\n Enter emp no: ";
cin>>empno;
cout<<"\n Enter emp name: ";
cin>>name;
cout<<"\n Enter emp Salary: ";
cin>>sal;
}
void show(emp x) //friend fun. definition
{
cout<<"\n Emp No= "<<x.empno;
cout<<"\n Emp Name= "<<x.name;
cout<<"\n Emp Salary="<<x.sal;
}
void main( )
{
clrscr( );
emp p;
p.get( );
show(p); //call to friend fun.
getch( );
}

14
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

➢ Single Friend function for multiple classes:


• We can declare single friend function for multiple classes to access all data (public,
private and protected) of all classes in single friend function.
• If we have to access data of classes in single friend function then same friend function
must be declared in all or every classes.
Following program demonstrate the use of single friend function for multiple classes:

#include<iostream.h>
#include<conio.h>
class company; //advance declaration
class emp
{
int empno;
char name[20];
float sal;
friend void show(emp,company); //friend fun. declaration
public:
void eget( );
};
class company
{
char cname[20];
char cadd[20];
friend void show(emp,company); //friend fun. declaration
public:
void cget( );
};
void emp::eget( )
{
cout<<"\n Enter emp no: ";
cin>>empno;
cout<<"\n Enter emp name: ";
cin>>name;
cout<<"\n Enter emp Salary: ";
cin>>sal;
}
void company::cget( )
{
cout<<"\n Enter Company Name: ";
cin>>cname;
cout<<"\n Enter Company Address: ";
cin>>cadd;
}
void show(emp x, company y) //friend fun. definition
{
cout<<"\n Emp No= "<<x.empno;
cout<<"\n Emp Name= "<<x.name;
cout<<"\n Emp Salary="<<x.sal;
cout<<"\n Company Name="<<y.cname;
cout<<"\n Company Address="<<y.cadd;
}
void main( )
{
clrscr( );
emp p;
company q;
p.eget( );
q.cget( );
show(p,q); //call to friend fun.
getch( );
}

15
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

➢ Friend Class:
• As like friend function, we are also able to declare a class as ‘friend’ of another class.
• If ‘first’ class declared, ‘second’ class as my friend then all the data of ‘first’ class can
easily accessed by the member function of ‘second’ class.
• But the data of ‘first’ class is accessed by member functions of ‘second’ class by using
only object of ‘first’ class.
• The friend class is declared in any section of class either in public, protected or private
• Friend class is declared by using the ‘friend’ keyword.
• In short, If class ‘A’ declares class ‘B’ is my friend then the member functions of class
‘B’ access all the data of class ‘A’.
• Syntax:

friend class class_name;

Here,
‘friend’ is keyword which is used to declare a friend class.
‘class’ is also keyword.
‘class_name’ is name of class which is an identifier.
Following program shows the use of friend class:

#include <iostream.h>
#include<conio.h>
class A
{
// ‘A’ declares ‘B’ as a friend... therefore A class data is accessed in B
int a,b,c;
friend class B; // declaration of friend class
public:
void get( );
};

class B
{
public:
void all(A);

};
void A::get( )
{
cout<< “\nEnter two no” ;
cin>>a>>b;
}

void B::all(A z)
{
z.c = z.a + z.b;
cout<<”\n Addition=”<< z.c;
}

void main( )
{
clrscr( );
A p;
B q;
p.get( );
q.all(p);
getch( );
}

16
B.Sc.II (Sem-iii) Year: 2020 OOPS lalita bhosale

Assignment: 2

1. What is class and object? How they differ from each other?
2. Define: “Member function” and “Non member function”
3. In how many ways we define member function class? Write difference between them.
4. What is inline function? Write its characteristics and advantage. Write a program to
make outside define function as inline.
5. What is access specifier (Visibility mode)? Explain all accessibility in details
6. What is array of object? Explain with example.
7. What is pointer to object? Explain with example.
8. What is nesting of class? Explain with example.
9. What is variable? Explain types of variable in C++ language.
10. Explain different parameter passing techniques in C++ language.
11. What is default argument? Explain its advantage with one example.
12. Write a program which demonstrates the function accepting and returning object.
13. What is dynamic memory allocation? How it is done in C++ language?
14. What is function overloading? List out its characteristics with one example.
15. What is friend function? List out its characteristics with one example.
16. Explain in details “Friend class”
17. Write the difference between friend function and member function.
18. Write a program that shows use of single friend function for multiple classes.
19. Write a program that demonstrate passing object as pass by value, pass by pointer and
pass by reference.

17

You might also like