Data hiding is the fundamental concept of object-oriented programming. It means a class private or protected data can access within that class or that class members only.
A class private or protected data
cannot be accessed in outside the class or another class. To access the private
data in outside class or another class, C++ provides the feature called friend
functions and friend classes.
Friend Functions
- In general, class private or protected members are not accessed in outside of the class or another class.
- To access the private members of a class in outside the class, C++ provides the feature called “Friend functions‟.
- A friend function is not a member function of a class, that is, it is a non-member function of the class. But it can access the private members of a class.
- A friend function is declared inside the public specifier of the class and is defined (implemented) outside the class as an ordinary function.
- A friend function is identified by the keyword "friend" followed by function declaration.
- A friend function is declared within a class.
Syntax for a friend function is
class class_name
{
Public:
friend return_type fun_name(args_list);
………
};
return_type fun_name(args_list)
{
statements;
}
}
//Demonstration on friend function
#include<iostream.h>
#include<conio.h>
class sample
{
private:
int n;
public:
sample()
{
n=0;
}
sample(int k) {
n=k;
}
void show(char *msg)
{
cout<<"\n"<<msg<<n;
}
friend int add(sample, sample);
};
int add(sample x, sample y)
{
return x.n+y.n;
}
void main()
{
clrscr();
sample s1(10),s2(40);
s1.show("s1 : ");
s2.show("s2 : ");
cout<<"\n s1+s2 = "<<add(s1,s2); getch();
}
Friend Class
· In general, class
private or protected members cannot be accessed by the members of another
class. To access those members, C++ provides the “friend classes‟.
·
A friend class can
access the private members of another class.
·
To declare a friend
class, use the keyword “friend‟.
Syntax:-
friend class classname;
·
A friend class is
declared in another class for which it is to be friend.
Ex.
class A
{
friend class B;
………
};
class B
{
………
.…….
};
·
Similar to friend
functions, a class can be friend to any number of classes.
· When you declare a class as friend, then all its members also became the friend of the other class.A friendship must always be explicitly specified (defined).A friendship is not transitive.
Ex. //Adding two objects of a class using friend function
#include<iostream.h>
#include<conio.h>
class first
{
private: int n; public:
first()
{
n=0;
}
first(int k)
{
n=k;
}
void show(char *msg)
{
cout<<"\n"<<msg<<n;
}
friend class second;
};
class second
{
public:
int add(first x, first y)
{
return x.n+y.n;
}
};
void main()
{
clrscr();
first f1(10),f2(40);
f1.show("f1 : ");
f2.show("f2 : ");
second s;
cout<<"\nf1+f2 = "<<s.add(f1,f2);
getch();
}
0 comments:
Post a Comment