C++ Class and Friend Function

Typically when you create a class and its variables or methods are private, no other class can access them.

In C++, there is a concept of a friend function which if declared in a class, it can be used by other classes to access private methods.

Use Sparingly

Class with a friend function

class date
{
  
     int day, //internal storage scheme
                  month, //this is private to the class
         
year;

          char *message; //string message reflecting date

         friend char* gdate(date); //declare outside access function


   public:
     void new_date(int,int,int); //method to change the date

          char* give_date(); //report date

          date(int); //constructor to set day only

     ~date(); //destructor

};

Now define the friend function (not a method)

char* gdate(date d)
{
     char* buffer = new char[15];
     sprintf(buffer,"%2d-%2d-%4d", d.month,d.day,d.year);
     return buffer;

}

Now define the methods

date::~date()
{
     delete message; //return allocated memory to free memory

}

date::date(int d)
{
   day = d;

}

void date::new_date(int d, int m, int y)
{
   day = d;
   month=m;
   year=y;
}

void date::give_date()
{
   char *buf= new char[80];

   sprintf(buf, "%s %d, %d", mname[month],day,year);


   return buf;
}

 

Main function that uses friend function

main()
{
     date d(12,29,2019); //create date object

     char *gdate(date); //declare friend functions

     cout << gdate(d) << "\n"; //use friend function

}

 

© Lynne Grewe