FRIEND FUNCTION

A non member function may not possess an access to the private data of a class . But , there could possibly be a scenario in which we want two classes to share a specific function . To illustrate , take into account a case where two classes , supervisor and Warden , are defined . We want to use a function Salary( ) to work on the object of both these classes . In this kind of situations , C++ enables the common function to be created friendly with the two the classes , thus enabling the function to have accessibility to the private data of these classes . This kind of a function will not need to be member of any of these classes .

Syntax:

class ABC
{
.....
.....
public:
.....
.....
friend void xyz(void);
};


STATIC MEMBER FUNCTION

Similar to static member variable , you can have static member function . When we declare a member of a class as static it implies regardless of how many objects of the class are built ,there is certainly just one copy of the static member . 

A static member is shared by all objects of the class . Almost all static data is initialized to zero whenever the first object is created , in the event that no other initialization exists. We can't place it in the class definition however it can be initialized outside the class. A member function which is declared static possesses the following characteristics : 



  • A static function will surely have access to just static members declared in the class . 
  • Syntax- class-name : : function-name ; 
Example:


#include <iostream>

using namespace std;

class Cuboid
{
   public:
      static int objectCount;
      // Constructor definition
      Cuboid(float a=2.0, float b=2.0, float c=2.0)
      {
         cout <<"Constructor called." << endl;
         length = a;
         breadth = b;
         height = c;
         // Increase every time object is created
         objectCount++;
      }
      float Volume()
      {
         return length * breadth * height;
      }
   private:
      float length;     // Length of a Cuboid
      float breadth;    // Breadth of a Cuboid
      float height;     // Height of a Cuboid
};

// Initialize static member of class Cuboid
int Cuboid::objectCount = 0;

int main(void)
{
   Cuboid Cuboid1(3.3, 1.2, 1.5);    // Declare Cuboid1
   Cuboid Cuboid2(8.5, 6.0, 2.0);    // Declare Cuboid2

   // Print total number of objects.
   cout << "Total objects: " << Cuboid::objectCount << endl;

   return 0;
}


0 comments to "FRIEND AND STATIC FUNCTIONS"

Post a Comment

Powered by Blogger.