Friend Concept and ‘mutable’ Keyword in C++
Friend:-
- By using a friend concept we can access a private member of a class.
- There are multiple types of a members can be friend of our class.
1) A friend can be any member function of a class.
2) A friend can be any function which is not a part of any class.
3) Whole class can be a friend of our class.
- Before using friend we have to use a forward declaration means we have to declare friend class at the start of a program.
class friend_class;
void fun(friend_class *fp)
{
cout<<”this is outside a fun which is not a part of any class.”;
cout<<fp->i;
}
class base
{
public:
void gun(friend_class *fp)
{
cout<<”this is member function of a class.”;
cout<<fp->i;
}
};
class demo
{
public:
void sun(friend_class *fp)
{
cout<<”this is a function of a class which is friend of another class.”;
cout<<fp->i;
}
};
class friend_class
{
private:
int i;
public:
friend_class()
{
i=10;
}
friend void fun(friend_class *);
friend void base::gun(friend_class *);
friend class demo;
};
int main()
{
friend_class fc;
fun(&fc);
base b;
b.gun(&fc);
demo d;
d.sun(&fc);
}
Output:-
this is outside a fun which is not a part of any class.
10 // private member of a friend_class class.
this is member function of a class.
10 // private member of a friend_class class.
this is a function of a class which is friend of another class.
10 // private member of a friend_class class.
Use of a friend in a nested class:-
- When we write a nested class, inner class members are unable to access private members of an outer class.
- To give access to such a private member we can declare that inner class as a friend of our class.
- This is the best usage of friend functionality.
class outer
{
private:
int i;
public:
outer()
{
i=10;
}
class inner;
friend class inner;
class inner
{
public:
void fun(outer *fp)
{
cout<<fp->i;
}
};
};
int main()
{
outer o;
outer::inner io;
io.fun(&o); // 10
return 0;
}
‘mutable’ Keyword:-
- When we declare a member function as a constant function, we cannot change contents of a caller object.
- If we want to change a contents we have to declare that variable as a mutable variable.
e.g.
class demo
{
public:
int i;
mutable int j;
demo()
{
i=10;
j=20;
}
void fun() const
{
i++; // error
j++; // 21 allowed
}
};
int main()
{
demo d;
d.fun();
}
For more reading about technology news in singapore and seo to online marketing do view more about other pages.
