Friend Function in C++

Friend Function in C++

Friend Function in C++

 

friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes.

A friend function is the function which is declared within a class and is defined outside the class .It
does not require any scope resolution operator for defining . It can access private members of a class. It is declared by using keyword “friend”.

The keyword “friend” is placed only in the function declaration of the friend function and not in the function definition or call. A friend function is called like an ordinary function. It cannot be called using the object name and dot operator. However, it may accept the object as an argument whose value it wants to access. A friend function can be declared in any section of the class i.e. public or private or protected.

 

SYNTAX :

 

friend return_type function_name (arguments);


CODE :
// C++ program to demonstrate the working of friend function

#include <iostream>
using namespace std;

class Distance {
    private:
        int meter;
        
        // friend function
        friend int addFive(Distance);

    public:
        Distance() : meter(0) {}
        
};

// friend function definition
int addFive(Distance d) {

    //accessing private members from the friend function
    d.meter += 5;
    return d.meter;
}

int main() {
    Distance D;
    cout << "Distance: " << addFive(D);
    return 0;
}

Output

Distance: 5

 

Topics Covered :

  • friend function in c++
  • friend functions
  • friend function in c++ with example
  • oop friend function
  • programming for beginners
  • object oriented programming
  • programming tutorial

 

 


 

 


 

Thanks for reading this blog. Hope you get satisfied with the blog and definitely this blog must have valued your time and effort of reading.

Take a time to connect our other digital creations such as Instagram , Facebook and Youtube.

 

🧑‍💻🧑‍💻 Social Media Links of Tech DCode :

👉🏻 YouTube : https://www.youtube.com/channel/UCjJnEdeugftBwQ3yMuD4B_A
👉🏻 Instagram : https://www.instagram.com/thetechdcode/
👉🏻 Facebook Page : https://www.facebook.com/thetechdcode
👉🏻 Twitter : https://twitter.com/thetechdcode
👉🏻 Telegram Channel : https://t.me/thetechdcode
👉🏻 Tech DCode Linktree : https://linktr.ee/thetechdcode
👉🏻 My Personal Handles : https://linktr.ee/virtualshivamin

🧑‍💻🧑‍💻 Social Media Links of SHIVAM SINGH (OWNER) :

👉🏻 Instagram : https://www.instagram.com/virtualshivamin/
👉🏻 Facebook Page : https://www.facebook.com/virtualshivamin/
👉🏻 Twitter : https://twitter.com/virtualshivamin/
👉🏻 Personal Linktree : https://linktr.ee/virtualshivamin 

 

Leave a Reply

Your email address will not be published. Required fields are marked *