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