Friends in C++ Classes
Object Oriented Programming in C++ – Part 6
Forward: In this article I show you how to make friends in C++.
By: Chrysanthus Date Published: 23 Aug 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
Making Friends
To make a function or class a friend to a particular class, just type the prototype of that function or the prototype of the class, in the description of the particular class, preceding the prototype, with the keyword, friend (and a space). That is all. After that the friend function or friend class can access the protected and private members of the particular class. We shall look at some examples.
Friend Function
In the following code, the function myFn() is a friend to the class MyClass.
#include <iostream>
using namespace std;
class MyClass
{
protected:
int num1;
private:
int num2;
friend int myFn();
};
int myFn()
{
MyClass myObj;
myObj.num1 = 2;
myObj.num2 = 3;
cout << myObj.num1<<"\n"<<myObj.num2;
}
int main()
{
myFn();
return 0;
}
Read through the above code and try it. It should compile and give you results. To declare (make) an external function a friend to a class, in the class description you type the prototype of the function, preceded by the keyword, friend (and a space). In the above code, myFn() is a friend to MyClass. So, in the definition of myFn() the protected and private members of MyClass have been accessed.
In the following code, HisClass is a friend to MyClass:
#include <iostream>
using namespace std;
class MyClass
{
protected:
int num1;
private:
int num2;
friend class HisClass;
};
class HisClass
{
public:
void myMthd()
{
MyClass myObj;
myObj.num1 = 2;
myObj.num2 = 3;
cout << myObj.num1<<"\n"<<myObj.num2;
}
};
int main()
{
HisClass hisObj;
hisObj.myMthd();
return 0;
}
Read through the above code and try it. It should compile and give you results. To declare (make) a class a friend to a particular class, in the class description you type the name of the class, preceded by the keyword, friend, a space and the keyword, class. In the above code, HisClass is a friend to MyClass. So, in the description of HisClass the protected and private members of MyClass have been accessed.
We take a break here and continue in the next part of the series.
Chrys
Related Courses
C++ CourseRelational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem
NEXT