What is the concept of friend function? How it violates the data hiding principle? Justify with example.

Answers

This answer is not selected as best answer. This answer may not be sufficient for exam.

Your limit has been exceed. We have implemented this system because, We got difficulty on managing our servers. Please donate some amount to remove this limit.

Quota: 0 / 30

Donate

A friend function is a function that is specified outside a class but has the ability to access the class member’s protected and private data. A friend can be a member’s function, function template, or function, or a class or class template, in which case the entire class and all of its members are friends.

Syntax:

class className{
      // Other Declarations
      friend returnType functionName(arg list);
};

In C++, a friend function is a function that has access to all members of the class that declares it a friend. In other words, a friend function is an honorary class member, able to see and do all the things members can do, without being a member itself.

Let’s take an example:

#include <iostream>

using namespace std;

class Box{
    double width;

    public:
        friend void printWidth(Box box);
        void setWidth(double wid);
};

void Box::setWidth(double wid){
    width = wid;
}

// Note: printWidth() is not a member function of any class.
void printWidth(Box box){
    /* Because printWidth() is a friend of Box, it can
    directly access any member of this class */
    cout << "Width of box : " << box.width << endl;
}

// Main function for the program
int main(){
    Box box;

    // set box width without member function
    box.setWidth(10.0);

    // Use friend function to print the wdith.
    printWidth(box);

    return 0;
}

The output of above program is

Width of box : 10
If you found any type of error on the answer then please mention on the comment or submit your new answer.
Leave your Answer:

Click here to submit your answer.

Discussion
0 Comments
  Loading . . .