Memory Allocation for Objects:
Member functions are allocated memory at the time of class definition. No separate memory allocation is done for functions for each object. Hence, memory allocation for data members is done only at the time of object creation.
Static Data Members:
Static data members have the following characteristics:
- They are initialized to zero when the first object of class is created. No other initialization is permitted.
- Only one member of that member is created for entire class and is shared by all the objects of that class.
- It is visible only within the class, but its lifetime is the entire program.
- The definition of the static data members is to be done outside the class definition.
//Example C++ program demonstrating Static Data Members
#include<iostream.h>
class item
{
static int count; //declaration of static variable
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void getcount(void)
{
cout<< “count:”;
cout<< count<< “n”;
}
};
int item::count; //definition of static variable
main()
{
item a,b,c; //count is initialized to zero at the time creation of ‘a’
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<< “After reading data”<< “n”;
a.getcount();
b.getcount();
c.getcount();
}
Static Member Functions
Characteristics of Static Member Functions:
- Static member function can have access to only other static members (data and functions) declared in the same class.
- Static member function can be called using the class name(instead of object name) like below:
class_name::functionName;
//C++ program demonstrating Static Member Functions
#include<iostream.h>
class test
{
` int code;
static int count;
public:
void setcode(void)
{
code=++count;
}
void showcode(void)
{
cout<< “object number:” <<code<< “\n”;
}
static void showcount(void) //static member function
{
cout<< “count:” <<count<< “\n”;
}
};
int test:: count;
main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test::showcount(); //calling of static function
test t3;
t3.setcode();
test::showcount();
t1.showcode();
t2.showcode();
t3.showcode();
}