You are on page 1of 42

Static Variable

A static local variable has the visibility of an


automatic local variable (that is, inside the
function containing it)
 However, its lifetime is the same as that of a
global variable, except that it doesn’t come into
existence until the first call to the function
containing it.
There after it remains in existence for the life of
the program.
Static Variable
float getavg(float); //declaration
int main()
{
float data=1, avg;
while( data != 0 )
{
cout << "Enter a number: ";
cin >> data;
avg = getavg(data);
cout << "New average is " << avg << endl;
}
return 0;
}
Static Variable
float getavg(float newdata)
{
static float total = 0; //static variables are initialized
static int count = 0; // only once per program

count++; //increment count


total += newdata; //add new data to total
return total / count; //return the new average
}
Static Variable
The use of static inside a function is the simplest. It simply
means that once the variable has been initialized, it remains in
memory until the end of the program. You can think of it as
saying that the variable sticks around, maintaining its value,
until the program completely ends.
For instance, you can use a static variable to record the
number of times a function has been called simply by including
the lines static int count =0; and count++; inside the function.
Because count is a static variable, the line "static int count =
0;" will only be executed once. Whenever the function is
called, count and total will have the last value assigned to it.
Static Class Data
 Static class member data is used to share information among
the objects of a class.
 Having said that each object contains its own separate data,
we must now amend that slightly.
 If a data item in a class is declared as static, only one such
item is created for the entire class, no matter how many
objects there are.
 A static data item is useful when all objects of the same class
must share a common item of information.
 A member variable defined as static has characteristics similar
to a normal static variable:
 It is visible only within the class, but its lifetime is the entire
program. It continues to exist even if there are no objects of
the class
Static class data
Example 2
class foo {
private:
static int count;
public:
foo() {
count++;
}
int getcount()
{
return count;
}
};
Example 2…
int foo::count = 0; // declaration outside the class

int main()
{
foo f1, f2, f3;
cout << “f1 count is " << f1.getcount() << endl;
cout << “f2 count is " << f2.getcount() << endl;
cout << “f3 count is " << f3.getcount() << endl;
return 0;
}
Separate Declaration and Definition
Static member data requires an unusual format
Ordinary variables are usually declared (the compiler is told
about their name and type) and defined (the compiler sets aside memory to hold

the variable) in the same statement.

 Static member data requires two separate


statements.
The variable’s declaration appears in the class
definition, but the variable is actually defined outside
the class, in much the same way as a global variable.
Separate Declaration and Definition
Why is this two-part approach used?
If static member data were defined inside the class (as it
actually was in early versions of C++), it would violate the idea
that a class definition is only a blueprint and does not set aside
any memory.
 Putting the definition of static member data outside the class
also serves to emphasize that the memory space for such data
is allocated only once before the program starts to execute, and
that one static member variable is accessed by an entire class
Each object does not have its own version of the variable, as it
would with ordinary member data.
Friend Functions
Introduction
Normally, we declare class data as private.
The non-member functions should not be able
to access an object’s private data.
The policy is, if you are not a member, you
can’t get it.
Sometimes, we need to relax this rigid policy.
Means we want to access an object’s private
data through non-member functions.

12
Friend Functions
A friend is a function that is not a member of a
class, but has access to the private members
of the class.
A friend function of a class can be a global
function.
Access specifier do not apply to the friends of
a class.
This friendship is unidirectional.

13
Creating Friends
 Step-1: Place a prototype in the class
declaration, prefixing the declaration with the
keyword friend.
 Step-2: Write the function definition.

14
Example

15
16
Note
 A friend keyword should appear in the prototype only
and not in the definition.
 Since it is a non-member function of the class of which
it is a friend, it can be prototyped in either the private
or public section of the class.
 A friend function takes one extra parameter as
compared to a member function that performs the
same task. This is because it cannot be called with
respect to any object. Instead, the object itself
appears as the parameter in the function call.
17
Example 2

18
Friend
Function

19
20
Out Put

21
Example-3
#include <iostream.h>

class Point
{
int x,y; A friend function
of Point class

public:
void print();

friend void setValue(Point &);


};

22
void Point::print()
{
cout<<"X="<<x<<endl;
cout<<"Y="<<y<<endl;
} Not a member of
any class. Global
void setValue(Point &p) Function. But it can
{ access private data
p.x = 5; of Point class.
p.y = 2;
}

int main()
{
Point obj;
setValue(obj);
obj.print();
return 0;
}

23
Example-4
#include <iostream.h>
class Beta;
class Alpha
{
int data;
public: A friend function
Alpha() of Alpha class
{
data=3;
}

friend int friFunc(Alpha, Beta);


};

24
class Beta
A friend function
{ int data; of Beta class
public:
Beta()
{
data=7;
}

friend int friFunc(Alpha, Beta);


};
int friFunc(Alpha a, Beta b)
{
return a.data+b.data;
}

25
Not a member of
any class. Global
int friFunc(Alpha a, Beta b) Function. But it can
{ access private data
of Alpha & Beta
return a.data+b.data; class.
}

int main()
{
Alpha obja;
Beta objb;
cout<<"Sum="<<friFunc(obja,objb)<<endl;
return 0;
}
26
Summery
In principle, private and protected members of a class
cannot be accessed from outside the same class in
which they are declared.
 However, this rule does not apply to "friends“
A non-member function can access the private and
protected members of a class if it is declared
a friend of that class.
That is done by including a declaration of this external
function within the class, and preceding it with the
keyword friend:
friend Classes
friend Classes

Similar to friend functions, a friend class is a


class whose members have access to the
private or protected members of another class
Friend Class

30
Rectangle class
values can be
accessed in
square

31
Friend Class
class Square;
class Rectangle
{ class Square
int width, height; {
public: friend class Rectangle;
private:
int area ()
int side;
{ public:
return (width * height); Square (int a) : side(a) {}
} };
void convert (Square a);
};

32
Friend Class
void Rectangle::convert (Square a)
{
width = a.side;
height = a.side;
}

int main ()
{
Rectangle rect;
Square sqr (4);
rect.convert(sqr);
cout << rect.area();
return 0;
}

33
 In this example, class Rectangle is a friend of
class Square allowing Rectangle's member functions to access
private and protected members of Square. More
concretely, Rectangle accesses the member
variable Square::side, which describes the side of the square
 There is something else new in this example: at the beginning
of the program, there is an empty declaration of class Square.
This is necessary because class Rectangle uses Square (as a
parameter in member convert),
andSquare uses Rectangle (declaring it a friend). 
 Friendships are never corresponded unless specified: In our
example, Rectangle is considered a friend class bySquare, but
Square is not considered a friend by Rectangle. Therefore, the
member functions of Rectangle can access the protected and
private members of Square but not the other way around. Of
course, Square could also be declared friend of Rectangle, if
needed, granting such an access.
Example-2 (cont’d)
 We want friFunc() to have access to both
classes’ private data members, so we make it a
friend function.
 Class Alpha and Beta are referred to in the
declaration of the function friFunc(), so we need to
declare these two classes:
– class Beta; //declaration in alpha.h
– class Alpha; //declaration in beta.h

35
Friend Class
 We can also declare a whole class to be a friend of
another class.
 All the member functions of the friend class will have
unrestricted access to the members of the class of
which it has been declare a friend.

36
Example
/* Header File (Alpha.h) */
class Beta;
class Alpha
{ A friend class of
Alpha class
int data;
public:
Alpha() { data=3; }
friend Beta;
};
37
Example (cont’d)
/* Header File (Beta.h) */
#include <iostream.h>
class Alpha;
Can access private
class Beta data of Alpha class

{
public:
void func1(Alpha a) {cout<<a.data; }
};
38
Example (cont’d)
/* Test Driver Program for Point class (driver.cpp) */
#include <iostream>
#include "Alpha.h "
#include "Beta.h"
using namespace std;
int main() {
Alpha obja;
Beta objb;
objb.func1(obja);
return 0;
}
39
friend class
class alpha {
private:
int data1;
public:
alpha() : data1(99) { } //constructor
friend class beta; //beta is a friend class
};
class beta {
public:
void func1(alpha a){ cout << "\ndata1=" << a.data1; }
void func2(alpha a){ cout << "\ndata1=" << a.data1; }
};
friend class
int main()
{
alpha a;
beta b;
b.func1(a);
b.func2(a);
cout << endl;
return 0;
}
friend class
In class alpha the entire class beta is
proclaimed a friend. Now all the member
functions of beta can access the private data
of alpha

You might also like