This is a C++ program that demonstrates the use of friend functions to access private data members of a class, Distance. The program defines a class Distance with a private integer data member (meter) and a constructor to initialize it to zero. The program also defines a friend function addFive, which takes an object of class Distance as its argument, adds 5 to its private data member (meter) and returns the updated value.
In the main function, the program creates an object of class Distance and calls the addFive function, passing the object as an argument. The addFive function then accesses the private data member of the Distance object using the friend declaration, adds 5 to it and returns the updated value, which is printed in the main function.
#include<iostream> using namespace std; class Distance { private: int meter; public: Distance(): meter(0) { } friend int addFive(Distance); }; int addFive(Distance d) { d.meter += 5; return d.meter; } int main() { Distance D; cout<<"Distance: "<< addFive(D); return 0; }To download raw file Click Here
Distance: 5
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions