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

book
The 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
#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();
}
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
class KeyManager {
public:
KeyManager(const std::string& key) : encryptionKey(key) {}
private:
std::string encryptionKey;
};
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
#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;
};
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.

question mark

What is the friend keyword used for?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 7
some-alt