Add friend function to access private members - C++ Class

C++ examples for Class:friend

Description

Add friend function to access private members

Demo Code

#include <iostream>
#include <cmath>
using namespace std;
// declaration section
class Complex/*from   w w w  . ja  va 2 s  .c om*/
{
   // friends list
   friend double addReal(const Complex&, const Complex&);
   friend double addImag(const Complex&, const Complex&);
   private:
   double realPart;
   double imaginaryPart;
   public:
   Complex(double real = 0.0, double imag = 0.0)  // inline constructor
   {
      realPart = real;
      imaginaryPart = imag;
   }
   void showComplexValues();
};
// implementation section
void Complex::showComplexValues()
{
   char sign = '+';
   if (imaginaryPart < 0) sign = '-';
   cout << realPart << ' ' << sign << ' ' << abs(imaginaryPart) << 'i';
}
// friend implementations
double addReal(const Complex& a, const Complex& b)
{
   return(a.realPart + b.realPart);
}
double addImag(const Complex& a, const Complex& b)
{
   return(a.imaginaryPart + b.imaginaryPart);
}
int main()
{
   Complex a(3.2, 5.6), b(1.1, -8.4);
   double re, im;
   cout << "The first complex number is ";
   a.showComplexValues();
   cout << "\nThe second complex number is ";
   b.showComplexValues();
   re = addReal(a,b);
   im = addImag(a,b);
   Complex c(re,im);   // create a new Complex object
   cout << "\n\nThe sum of these two complex numbers is ";
   c.showComplexValues();
   return 0;
}

Result


Related Tutorials