Contenido del Curso
C++ OOP
C++ OOP
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
.
main
#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; } 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:
KeyManager
class KeyManager { public: KeyManager(const std::string& key) : encryptionKey(key) {} private: std::string encryptionKey; };
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.
KeyManager
CryptographicAlgorithm
#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.
¡Gracias por tus comentarios!