5.11 FRIEND FUNCTIONS

When we define a class with private data members, we have difficulty in handling them outside the class. If we want safety, there has to be restrictions. Nevertheless, there can be special cases or exceptions to the rule. Well, the concept of friend function has been introduced in the language for this purpose. Inside the class, we can declare a function as friend of that class. This function will be defined outside the class as independent function. It will be able to access private data members of the class.

Let us study the concept with the help of a program.

Problem: Write a program to compare two time objects. Develop method compare() to decide whether time t1 is equal to time t2 or not.

Solution: See Program 5.8.

Get Object Oriented Programming with C++, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.