friend functions and classes

Posted on April 19, 2013. Filed under: C++ | Tags: |

In C++, a class can give its own friendship to another class or to a function defined outside itself. The friend class and friend function then have access to the private class members (variables and functions) of the class that gives friendship. Like (almost) everybody are trying to (or forced to) give friendship to the king, the king didn’t give friendship to everybody; similarly, the c++ friendship is not mutual (why they don’t pick a better keywords such as privilege, access, etc.) –when class Joe set class King as friend, class King then can access class Joe’s private functions and modify class Joe’s private variables, which doesn’t mean class Joe can do the same to the class King.

The c++ friend keyword syntax is:
# include <iostream>
using namespace std;

class StankFist {
StankFist() {stinkyVar=0;}
int stinkyVar;

friend void stinkysFriend(StankFist &sfo);

void stinkysFriend(StankFist &sfo) {
cout<< sfo.stinkyVar<<endl;

int main() {
StankFist bob;


Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: