Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
The Friend Keyword | Encapsulation Overview
C++ OOP
course content

Course Content

C++ OOP

C++ OOP

1. Fundamentals of OOP
2. Constructors and Destructors
3. Encapsulation Overview
4. Inheritance Overview
5. Polymorphism Overview

bookThe Friend Keyword

The friend keyword stands as a unique construct, offering a departure from the standard encapsulation principles of object-oriented programming. It allows a function or another class to access private and protected members of a class.

cpp

main

copy
1234567891011121314151617
#include <iostream> class Example { private: const static int static_private_member = 0; friend void func(); // grants access to the private members to func() }; void func() { std::cout << Example::static_private_member << std::endl; } int main() { func(); }

Using this approach breaks encapsulation because it lets outside entities access the class members. However, there might be situations where it's necessary to do so. For instance:

h

KeyManager

copy
123456
class KeyManager { public: KeyManager(const std::string& key) : encryptionKey(key) {} private: std::string encryptionKey; };

In this example, the encryptionKey is kept private, and there is no accessor method provided because we want to prevent external access to it from outside the class. But what if there is a necessity to use an external algorithm for encrypting and decrypting, this is where the friend keyword comes into play.

h

KeyManager

h

CryptographicAlgorithm

copy
12345678910
#include "CryptographicAlgorithm.h" class KeyManager { public: KeyManager(const std::string& key) : encryptionKey(key) {} private: std::string encryptionKey; // Allow CryptographicAlgorithm access to private members friend class CryptographicAlgorithm; };

The most common use-case for friend keyword arises when quick fixes are required, and you intend to refactor it later. It's preferable to design your class relationships without relying on it, although specific scenarios may still occur.

What is the friend keyword used for?

What is the friend keyword used for?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 7
We're sorry to hear that something went wrong. What happened?
some-alt