How to Use Friend Functions in C++

C++ offers three levels of data access control inside a class. Private data isn't accessible by non-member functions or outside classes. But sometimes you need to access this data in a program, so you need to find a way to work around this C++ rule. The friend feature lets a programmer access private data. Read on to learn how to use friend functions in C++.

Things You'll Need

  • Intermediate C++
  • C++ compiler with an IDE

Instructions

    • 1

      Find a class that has private members. Remember that data that you don't declare under an access modifier is private by default:

      class Tutorial {

      int privateData; // this int is private and is insulated from the outside world

      public:

      Tutorial(): privateData(5); // default constructor initializes privateData to 5

      // ...

    • 2

      Allow a non-member function to read privateData in Step 1. A non-member function is any function that exists outside class Tutorial. Precede the declaration of that function by the friend keyword and insert the line in the private area of Tutorial:

      class Tutorial {

      int privateData;

      friend void Display(); // our non-member function

      // ...

      The private keyword tells class Tutorial that it can trust Display(), even though it is not one of its member functions.

    • 3

      Let another class access the private data of class Tutorial. The declaration of a friend class is similar. Precede the class declaration by the friend keyword and insert the line in the private data area of Tutorial:

      class Tutorial {

      int privateData;

      friend void Display();

      friend class Outside; // our external class

      // ...

      Now class Outside has access privileges to private data.

    • 4

      Study a C++ program that demonstrates the friend concepts, as in the following code:

      void Display() {

      Tutorial t;

      cout << t.privateData << endl;

      }

      class Outside {

      public:

      void Display() {

      Tutorial x;

      cout << x.Display() << endl;

      };

      main() {

      Display();

      Outside x;

      x.Display();

      }

    • 5

      See the result:

      5

      5

Tips & Warnings

  • Use friend with good judgment. Bjarne Stoustrup (the designer of C++) created the private access modifier for a good reason: encapsulation and data security. In other words, don't use "friend" as a hacker.
Related Searches

Resources

You May Also Like

Related Ads

Check It Out

Prep for Black Friday Checklist [Infographic]