You are on page 1of 11

TITLE

C++ & OOPS

SESSION 8
FRIEND FUNCTIONS & STATIC
MEMBERS
Static Data Member:
A data member of a class can be static.
It is initialized to zero when the first object
of the class is created. No other
initialization is permitted.
Only one copy of that member is created
for the entire class and is shared by all
objects of the class.
It is visible only within the class. Its
lifetime is till the program is terminated.

Static members are used to maintain the


values common to the entire class
It can be used as a counter that records
the occurrences of all the objects.
The type and scope of of each static
member variable must be defined out
side the class definition
Ex: int test :: count;
This is necessary because the static data
members are stored separately rather
than part of an object.
An initial value can be assigned to the
static variable Ex: int test :: count=10;
Ex:
class store
{ int x; static int count;
public: void getdata (int a)
{ x = a; count++;
}
};
int store :: count; //count defined.

The count is incremented whenever data


is read into an object.
STATIC MEMBER FUNCTION
Like static data member we can also
have static member functions.
A static member function can have
access to only other static members
declared in the same class.
A static member function can be called
using the class name.
Class name::function name;
Ex:class store
{ int code;
static int count;
public:
void setcode()
{ code = ++count;}
static void showcount()
{ cout<<”\ncount = “<<count; }
};
The function showcount() displays the
number of objects created till that moment .
Friendly Functions:
A non – member function cannot have
access to the private data of a class.
There could be a situation where two
classes have to share a particular function.
In such situations C++ allows a common
function made friendly with both the
classes.
Ex: class test
{
public: friend void tax ();
};
A friend function declaration must be
preceded by the keyword friend.
It is not in the scope of the class to which it
has been declared as friend.
It is not called using the object of that
class.
It can be invoked like a normal function
without any object.
It cannot access the member names
directly.
It has to use an object name dot
membership operator and member name.
It can be declared either in the public or
private part of the class without affecting
its meaning.
Usually it has the objects as arguments.
A friend function can be called by
reference. It should be used only when
absolutely necessary, because such
function alters the values of the private
members which is against data hiding.
Friend functions are often used in
operator overloading.
CONCLUSION
What we have learnt this session?
Static data members and member functions,
friendly functions.
What we will discuss next session?
Array data members and array of objects.

You might also like