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

The Friend KeywordThe 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.cpp

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.h

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

h

CryptographicAlgorithm.h

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?

Select the correct answer

Everything was clear?

Section 3. Chapter 7

The Friend KeywordThe 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.cpp

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.h

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

h

CryptographicAlgorithm.h

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?

Select the correct answer

Everything was clear?

Section 3. Chapter 7
some-alt