SlideShare a Scribd company logo
1 of 17
Download to read offline
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Women University of Azad Jammu and Kashmir Bagh
Department of Computer Sciences and Information Technology, Women University of Azad Jammu and Kashmir Bagh
www.wuajk.edu.pk
Object Oriented Programming
CS-3201
Dr. Anees Qumar Abbasi
aneesabbasi.wuajk@gmail.com
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Objects as Function Parameters
& Return Type
Friend Classes & Functions
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Object as Function Parameters
• Objects can also be passed as parameters to member functions.
• The method of passing objects to a functions as parameters is as
passing other simple variables.
• It will easily be understand by following example.
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Object as Parameter
void add(Travel p)
{
Travel t;
t.km=km+p.km;
t.hr=hr+p.hr;
cout<<“Total traveling
is ”<<t.km<<“ kilometers
in
”<<t.hr<<“ hours”<<endl;
}
};
void main()
{
Travel my, your;
my.get();
my.show();
your.get();
your.show();
my.add(your);
getch();
}
class Travel
{
private:
int km, hr;
public:
Travel()
{
km=hr=0;
}
void get()
{
cout<<“Enter Kilometers
traveled”;cin>>km;
cout<<“Enter Hours
traveled”;cin>>hr;
}
void show() {
cout<<“You traveled
”<<km<<“ in ”<<hr<<“
hours”<<endl;
}
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
How Program Works
void add(Travel p) {
Travel t;
t.km = km + p.km;
t.hr = hr + p.hr;
}
• Data members of temporary object t
• Data members of temporary object my
• Data members of temporary object p
• The above program declares to objects of class Travel and inputs data in both objects.
• The add() function accepts an object of type Travel as parameter.
• It adds the values of data members of the parameter object and the values of calling object’s data members
and displays the result.
• The working of member function add() is as follows:
Function call in main
my.add(your);
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Returning Objects from Member Function
• The method of returning an object from member function is same as
returning a simple variable.
• If a member function returns an object, its return type should be the
same as the type of object to be returned.
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Object as Parameter
Travel add(Travel p)
{
Travel t;
t.km=km+p.km;
t.hr=hr+p.hr;
return t;
}
};
void main()
{
Travel my, your, r;
my.get();
my.show();
your.get();
your.show();
r = my.add(your);
cout<<“Total travelling is as
follow:n”;
r.show();
getch();
}
class Travel
{
private:
int km, hr;
public:
Travel()
{
km=hr=0;
}
void get()
{
cout<<“Enter Kilometers
traveled”;cin>>km;
cout<<“Enter Hours
traveled”;cin>>hr;
}
void show() {
Cout<<“You traveled
”<<km<<“ in ”<<hr<<“
hours”<<endl;
}
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
• The add() function in the above program accepts a parameter object
of type Travel.
• It adds the contents of parameter and calling object and stores the
result in a temporary object.
• The function then returns the whole object back to main() function
that is stored in r.
• The program finally displays the result using r.show() statement.
How Program Works
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Classes
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.
We can declare a friend class in C++ by using the friend keyword.
friend class class_name; // declared in the base class
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Friend Class
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
// friend class declaration
friend class F;
};
// Here, class F is declared as a
friend inside class GFG. Therefore,
F is a friend of class GFG. Class F
can access the private members of
class GFG.
class F {
public:
void display(GFG& t)
{
cout << "The value of Private Variable
= "<< t.private_variable << endl;
cout << "The value of Protected
Variable = "<< t.protected_variable;
}
};
// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;
} Output:
The value of Private Variable = 10
The value of Protected Variable = 99
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Function
Like a friend class, a friend function can be granted special access to private and
protected members of a class in C++. They are the non-member functions that can
access and manipulate the private and protected members of the class for they are
declared as friends.
A friend function can be:
1. A global function
2. A member function of another class
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Function
Syntax:
friend return_type function_name (arguments); // for a global function
or friend return_type
class_name::function_name (arguments);// for a member function of other class
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Friend Function
1. Global Function as Friend Function
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
{
private_variable = 10;
protected_variable = 99;
}
// friend function declaration
friend void friendFunction(base&
obj);
};
// friend function definition
void friendFunction(base& obj)
{
cout << "Private Variable:" <<
obj.private_variable<< endl;
cout << "Protected Variable:" <<
obj.protected_variable;
}
int main()
{
base object1;
friendFunction(object1);
return 0;
}
Output:
Private Variable: 10
Protected Variable: 99
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Example: Friend Function
2. Member Function of Another Class a Friend Function
class anotherClass {
public:
void memberFunction();
};
// base class for which friend is
declared
class base {
private:
int private_variable;
protected:
int protected_variable;
public:
base()
{ private_variable = 10;
protected_variable = 99; }
// friend function declaration
friend void
anotherClass::memberFunction();
};
// friend function definition
void anotherClass::memberFunction(base&
obj)
{
cout << "Private Variable: " <<
obj.private_variable<< endl;
cout << "Protected Variable: " <<
obj.protected_variable;
}
Void main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);
}
Output:
Private Variable: 10
Protected Variable: 99
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Features of Friend Functions
q A friend function is a special function in C++ that in spite of not being a member
function of a class has the privilege to access the private and protected data of a
class.
q A friend function is a non-member function or ordinary function of a class, which is
declared as a friend using the keyword “friend” inside the class. By declaring a
function as a friend, all the access permissions are given to the function.
q The keyword “friend” is placed only in the function declaration of the friend function
and not in the function definition or call.
q A friend function is called like an ordinary function. It cannot be called using the
object name and dot operator. However, it may accept the object as an argument
whose value it wants to access.
q A friend function can be declared in any section of the class i.e. public or private or
protected.
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Functions
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.
Department of Computer Sciences & Information Technology
Dr. Anees Qumar Abbasi- Object-Oriented Programming
Friend Functions & Classes
v Friends should be used only for limited purposes. Too many functions or external
classes are declared as friends of a class with protected or private data access
lessens the value of encapsulation of separate classes in object-oriented
programming.
v Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of
A automatically.
v Friendship is not inherited.
v The concept of friends is not in Java.

More Related Content

Similar to Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf

Similar to Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf (20)

Oops concept
Oops conceptOops concept
Oops concept
 
Chapter23 friend-function-friend-class
Chapter23 friend-function-friend-classChapter23 friend-function-friend-class
Chapter23 friend-function-friend-class
 
Oop concept
Oop conceptOop concept
Oop concept
 
3. Polymorphism.pptx
3. Polymorphism.pptx3. Polymorphism.pptx
3. Polymorphism.pptx
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
oop lecture 3
oop lecture 3oop lecture 3
oop lecture 3
 
Class object
Class objectClass object
Class object
 
2nd puc computer science chapter 8 function overloading
 2nd puc computer science chapter 8   function overloading 2nd puc computer science chapter 8   function overloading
2nd puc computer science chapter 8 function overloading
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdf
 
Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
02.adt
02.adt02.adt
02.adt
 
Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2Object Oriented Programming using C++ - Part 2
Object Oriented Programming using C++ - Part 2
 
C++.pptx
C++.pptxC++.pptx
C++.pptx
 

More from AneesAbbasi14

Goal Setting UPDATED.pptx
Goal Setting UPDATED.pptxGoal Setting UPDATED.pptx
Goal Setting UPDATED.pptxAneesAbbasi14
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdfAneesAbbasi14
 
lecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdflecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdfAneesAbbasi14
 
lec07_transformations.pptx
lec07_transformations.pptxlec07_transformations.pptx
lec07_transformations.pptxAneesAbbasi14
 
Yasir Presentation.pptx
Yasir Presentation.pptxYasir Presentation.pptx
Yasir Presentation.pptxAneesAbbasi14
 
Lec_1,2_OOP_(Introduction).pdf
Lec_1,2_OOP_(Introduction).pdfLec_1,2_OOP_(Introduction).pdf
Lec_1,2_OOP_(Introduction).pdfAneesAbbasi14
 
IntroComputerVision23.pptx
IntroComputerVision23.pptxIntroComputerVision23.pptx
IntroComputerVision23.pptxAneesAbbasi14
 

More from AneesAbbasi14 (10)

Goal Setting UPDATED.pptx
Goal Setting UPDATED.pptxGoal Setting UPDATED.pptx
Goal Setting UPDATED.pptx
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
 
lecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdflecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdf
 
lec09_ransac.pptx
lec09_ransac.pptxlec09_ransac.pptx
lec09_ransac.pptx
 
lec07_transformations.pptx
lec07_transformations.pptxlec07_transformations.pptx
lec07_transformations.pptx
 
02-07-20_Anees.pptx
02-07-20_Anees.pptx02-07-20_Anees.pptx
02-07-20_Anees.pptx
 
Yasir Presentation.pptx
Yasir Presentation.pptxYasir Presentation.pptx
Yasir Presentation.pptx
 
Lec5_OOP.pptx
Lec5_OOP.pptxLec5_OOP.pptx
Lec5_OOP.pptx
 
Lec_1,2_OOP_(Introduction).pdf
Lec_1,2_OOP_(Introduction).pdfLec_1,2_OOP_(Introduction).pdf
Lec_1,2_OOP_(Introduction).pdf
 
IntroComputerVision23.pptx
IntroComputerVision23.pptxIntroComputerVision23.pptx
IntroComputerVision23.pptx
 

Recently uploaded

_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 

Recently uploaded (20)

_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

Lec_15_OOP_ObjectsAsParametersFriendClasses.pdf

  • 1. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Women University of Azad Jammu and Kashmir Bagh Department of Computer Sciences and Information Technology, Women University of Azad Jammu and Kashmir Bagh www.wuajk.edu.pk Object Oriented Programming CS-3201 Dr. Anees Qumar Abbasi aneesabbasi.wuajk@gmail.com
  • 2. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Objects as Function Parameters & Return Type Friend Classes & Functions
  • 3. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Object as Function Parameters • Objects can also be passed as parameters to member functions. • The method of passing objects to a functions as parameters is as passing other simple variables. • It will easily be understand by following example.
  • 4. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Example: Object as Parameter void add(Travel p) { Travel t; t.km=km+p.km; t.hr=hr+p.hr; cout<<“Total traveling is ”<<t.km<<“ kilometers in ”<<t.hr<<“ hours”<<endl; } }; void main() { Travel my, your; my.get(); my.show(); your.get(); your.show(); my.add(your); getch(); } class Travel { private: int km, hr; public: Travel() { km=hr=0; } void get() { cout<<“Enter Kilometers traveled”;cin>>km; cout<<“Enter Hours traveled”;cin>>hr; } void show() { cout<<“You traveled ”<<km<<“ in ”<<hr<<“ hours”<<endl; }
  • 5. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming How Program Works void add(Travel p) { Travel t; t.km = km + p.km; t.hr = hr + p.hr; } • Data members of temporary object t • Data members of temporary object my • Data members of temporary object p • The above program declares to objects of class Travel and inputs data in both objects. • The add() function accepts an object of type Travel as parameter. • It adds the values of data members of the parameter object and the values of calling object’s data members and displays the result. • The working of member function add() is as follows: Function call in main my.add(your);
  • 6. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Returning Objects from Member Function • The method of returning an object from member function is same as returning a simple variable. • If a member function returns an object, its return type should be the same as the type of object to be returned.
  • 7. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Example: Object as Parameter Travel add(Travel p) { Travel t; t.km=km+p.km; t.hr=hr+p.hr; return t; } }; void main() { Travel my, your, r; my.get(); my.show(); your.get(); your.show(); r = my.add(your); cout<<“Total travelling is as follow:n”; r.show(); getch(); } class Travel { private: int km, hr; public: Travel() { km=hr=0; } void get() { cout<<“Enter Kilometers traveled”;cin>>km; cout<<“Enter Hours traveled”;cin>>hr; } void show() { Cout<<“You traveled ”<<km<<“ in ”<<hr<<“ hours”<<endl; }
  • 8. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming • The add() function in the above program accepts a parameter object of type Travel. • It adds the contents of parameter and calling object and stores the result in a temporary object. • The function then returns the whole object back to main() function that is stored in r. • The program finally displays the result using r.show() statement. How Program Works
  • 9. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Friend Classes 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. We can declare a friend class in C++ by using the friend keyword. friend class class_name; // declared in the base class
  • 10. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Example: Friend Class class GFG { private: int private_variable; protected: int protected_variable; public: GFG() { private_variable = 10; protected_variable = 99; } // friend class declaration friend class F; }; // Here, class F is declared as a friend inside class GFG. Therefore, F is a friend of class GFG. Class F can access the private members of class GFG. class F { public: void display(GFG& t) { cout << "The value of Private Variable = "<< t.private_variable << endl; cout << "The value of Protected Variable = "<< t.protected_variable; } }; // Driver code int main() { GFG g; F fri; fri.display(g); return 0; } Output: The value of Private Variable = 10 The value of Protected Variable = 99
  • 11. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Friend Function Like a friend class, a friend function can be granted special access to private and protected members of a class in C++. They are the non-member functions that can access and manipulate the private and protected members of the class for they are declared as friends. A friend function can be: 1. A global function 2. A member function of another class
  • 12. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Friend Function Syntax: friend return_type function_name (arguments); // for a global function or friend return_type class_name::function_name (arguments);// for a member function of other class
  • 13. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Example: Friend Function 1. Global Function as Friend Function class base { private: int private_variable; protected: int protected_variable; public: base() { private_variable = 10; protected_variable = 99; } // friend function declaration friend void friendFunction(base& obj); }; // friend function definition void friendFunction(base& obj) { cout << "Private Variable:" << obj.private_variable<< endl; cout << "Protected Variable:" << obj.protected_variable; } int main() { base object1; friendFunction(object1); return 0; } Output: Private Variable: 10 Protected Variable: 99
  • 14. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Example: Friend Function 2. Member Function of Another Class a Friend Function class anotherClass { public: void memberFunction(); }; // base class for which friend is declared class base { private: int private_variable; protected: int protected_variable; public: base() { private_variable = 10; protected_variable = 99; } // friend function declaration friend void anotherClass::memberFunction(); }; // friend function definition void anotherClass::memberFunction(base& obj) { cout << "Private Variable: " << obj.private_variable<< endl; cout << "Protected Variable: " << obj.protected_variable; } Void main() { base object1; anotherClass object2; object2.memberFunction(object1); } Output: Private Variable: 10 Protected Variable: 99
  • 15. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Features of Friend Functions q A friend function is a special function in C++ that in spite of not being a member function of a class has the privilege to access the private and protected data of a class. q A friend function is a non-member function or ordinary function of a class, which is declared as a friend using the keyword “friend” inside the class. By declaring a function as a friend, all the access permissions are given to the function. q The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition or call. q A friend function is called like an ordinary function. It cannot be called using the object name and dot operator. However, it may accept the object as an argument whose value it wants to access. q A friend function can be declared in any section of the class i.e. public or private or protected.
  • 16. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Friend Functions 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.
  • 17. Department of Computer Sciences & Information Technology Dr. Anees Qumar Abbasi- Object-Oriented Programming Friend Functions & Classes v Friends should be used only for limited purposes. Too many functions or external classes are declared as friends of a class with protected or private data access lessens the value of encapsulation of separate classes in object-oriented programming. v Friendship is not mutual. If class A is a friend of B, then B doesn’t become a friend of A automatically. v Friendship is not inherited. v The concept of friends is not in Java.