Tutorial - C / C++ - Friends


Coding Friends Tutorial Index - > C / C++

Author Ian - Tutorial Posts = 62
A friend of a class allow access to the private members of that class, because there are some cases where this is required when the whole of the created class is required to be viewable, e.g. when a private member is not being able to set with the class methods.

To declare a friend within a class, for example to declare a function / class as a friend.
friend int FuncToFriendClass(int a);              // friend to the function.
friend class ClassToClassFriend;              // friend to a class

This will allow the function FuncToFriendClass to gain access to all objects within the class, and the class ClassToClassFriend as well.

The source code
---
int FuncToFriendClass(int a);              // declare the function, for the class to make a friend.

class FriendlyClass
{
private:
       int private_data;

       friend int FuncToFriendClass(int a);              // friend to the function.
       friend class ClassToClassFriend;              // friend to a class
public:
       FriendlyClass()
       {
              private_data = 5;
       }
};

int FuncToFriendClass(int a)
{
       FriendlyClass friendClass;                            // the friend to this funciton.
       return friendClass.private_data + a;
}

class ClassToClassFriend
{
public:
       int FriendClassPrivateDataMinus(int b)
       {
              FriendlyClass classFriend;
              return classFriend.private_data - b;
       }
};

int main()
{
       ClassToClassFriend classFriend;
       std::cout << "Friendly function to class =" << FuncToFriendClass(3) << "\n";
       std::cout << "Friendly class to class = " << classFriend.FriendClassPrivateDataMinus(2) << "\n";
       return 0;
}
---
If you save that as friend.cpp and then compile, the output will be
Friendly function to class = 8
Friendly class to class = 3
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search