C++ friend functions

Introduction

An individual function can be specified as a friend of a class, or a whole class can be specified as a friend of another class.

In the latter case, all the function members of the friend class have the same access privileges as a normal member of the class.

To make a function a friend of a class, you must declare it within the class definition using the friend keyword.

A friend function can be a global function or it can be a member of another class.

#include <iostream>
#include <memory>
class Pool//w  ww.  jav  a 2s.  c o  m
{
private:
  double length;
  double width;
  double height;
 
public:
  // Constructors
  Pool(double lv = 1.0, double wv = 1.0, double hv = 1.0);
 
  double volume();                                  // Function to calculate the volume of a pool
 
  friend double surfaceArea(const Pool& aPool);       // Friend function for the surface area
};
 
// Constructor definition
Pool::Pool(double lv, double wv, double hv) : length(lv), width(wv), height(hv)
{
  std::cout << "Pool constructor called." << std::endl;
}
 
// Function to calculate the volume of a pool
double Pool::volume()
{
  return length*width*height;
}
 
 
int main()
{
  Pool pool1 {2.2, 1.1, 0.5};                              // An arbitrary pool
  Pool pool2;                                              // A default pool
  auto pPool3 = std::make_shared<Pool>(15.0, 20.0, 8.0);   // Pool on the heap
 
  std::cout << "Volume of pool1 = " << pool1.volume() << std::endl;
  std::cout << "Surface area of pool1 = " << surfaceArea(pool1) << std::endl;
 
  std::cout << "Volume of pool2 = "<< pool2.volume() << std::endl;
  std::cout << "Surface area of pool2 = " << surfaceArea(pool2) << std::endl;
 
  std::cout << "Volume of pool3 = " << pool3->volume() << std::endl;
  std::cout << "Surface area of pool3 = " << surfaceArea(*pPool3) << std::endl;
}
 
// friend function to calculate the surface area of a Pool object
double surfaceArea(const Pool& aPool)
{
  return 2.0*(aPool.length*aPool.width + aPool.length*aPool.height +aPool.height*aPool.width);
}
#include <iostream>
using namespace std;
class beta;              //needed for frifunc declaration
class alpha/*from   w w w  . j a v  a  2  s .  co  m*/
{
   private:
   int data;
   public:
   alpha() : data(3) {  }            //no-arg constructor
   friend int frifunc(alpha, beta);  //friend function
};
class beta
{
   private:
   int data;
   public:
   beta() : data(7) {  }             //no-arg constructor
   friend int frifunc(alpha, beta);  //friend function
};
int frifunc(alpha a, beta b)            //function definition
{
   return( a.data + b.data );
}
int main()
{
   alpha aa;
   beta bb;
   cout << frifunc(aa, bb) << endl;     //call the function
   return 0;
}



PreviousNext

Related