Senerio:
ATM (Automated Teller Machine) machines are electronic outlets that allow customers to do their basic transactions without interaction of bank’s representative. While programming this ATM in C++, We have created a class named CUSTOMER which stores customer data (i.e. name, NIC, age, address, account balance and transaction history etc.). There is a friend function that wants to access some private information of the class.
Question:
Being a C++ developer, analyze the whole scenario, what do you think, does a friend function contradict the rules of Encapsulation?
Give your opinion in yes or no with strong reasons.
Yes, the Friend function contradicts the rules of encapsulation.
First of all, what is encapsulation? , Let us understand it with an example.
In normal terms, Encapsulation is defined as wrapping up data and information under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data and the functions that manipulate them.
Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section, etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales-related activities and keeps records of all the sales. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”.
Now in our case friend function directly wants to access the private data of the class. which is not allowed in the encapsulation scenario. There must be an interaction of the bank's representative, through which function could access the data. NOT directly.
That is why it contradicts the rules of Encapsulation.
Comments
Leave a comment