Length of Box using friend function in C++


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.

Source Code

#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

Output

Length of box: 10

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples