Find distance 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, 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.

Source Code

#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

Output

Distance: 5

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