Skip to main content

Static members

Those of you who are familiar with C, have used static keyword to mean opposite of automatic. A static variable has a lifetime of complete program execution. That is to say it does not get destroyed when you leave the block where it is defined.
What is static in C++?

Static storage

Automatic variables are destroyed when a function or block in which it is defined exits  where as static variables have static duration. That is they remain alive till the end of program. 


And static global variables and functions have internal linkage. That is they are visible only in the file they are defined in.  A non-static global variable or function has external linkage. It is visible in the entire program.

Let us discuss about static members of a class.
Static member of a class does not belong to an object, but belongs to the class.
Static data member


Ordinary data members are present in each object and they are different for each object. But a  static data member is shared by all objects of the class. There is only one copy of static data member.

To make a data member static, it should be defined with keyword static inside the class body.

A static data MUST also be defined outside the body of the class because inside class, the declaration of static data is not definition.

class SimpleInterest
{
 static double rate;/*static data declaration*/
 int amount;
 float period;
public:
 /*funnctions*/
};
double SimpleInterest::rate=0.07;/*definition*/

In the program above rate is a static data member. And it is defined outside SimpleInterest class using scope resolution operator .

Static data members can be accessed using dot or arrow operators like any other members but they can also be accessed without an object, using class name followed by scope resolution operator. In the above example, we can access rate as SimpleInterest::rate.

int main()
{
 SimpleInterest::rate=0.08;
 SimpleInterest obj(1000,1);
 float intrst = obj.amount*obj.period*obj.rate; 
 obj.rate = 0.085;
 cout<<obj.rate<<" ";
 SimpleInterest obj2(10000,5);
 cout<<obj2.rate;
}

Output:
0.085 0.085

In the example above, we are accessing rate using :: operator and dot operator. In first line of main() we accessed rate without creating any object. 

we are assigning a value to rate using ::. Then we are setting the value of rate using obj. When obj2.rate is printed, we see the same value 0.085.

This shows that, unlike other data members, static members are shared by all objects of a class. In this case, rate is one integer which is shared by all objects of SimpleInterest class. 

Try it out : Find out the size of a class with a static data member in it using sizeof() operator Does the size include this static member?

Static data member can not be mutable.

Static member functions:


A static member function is a method which can be invoked without using any object. Static function can be called directly using  class name and scope resolution operator.


But there is a catch. A static function can access only static data members. It can not access non-static data because it does not belong to an object. It has no "this" pointer.

A function is made static by using static keyword along with function declaration within the class body.

Rules for static functions.
  1. A static function can not use "this" pointer. Hence it can not access non-static data members.
  2. A static function can not be const
  3. Static function can not be virtual
class A
{
 int n;
 static int m;
public:
 A(int m);
 static void print() ;/*static function*/
};
int A::m=4;

void A::print()
{
 cout<<"Hello world";
 //cout<<n;/*error. Can not access n*/
 cout<<m;/*no error. m is static*/
}
int main()
{
 A::print();
}
 In the code shown above, we are not creating any object of A . We can still call the print() method of class A using class name. 

If in static function print(), we try to access n (a non-static member), we get a compilation error.  

Let us look at an example where a static function will help us to create objects even if we have only private constructor to a class

#include <iostream>
using namespace std; 
class A
{
 int m;
 A(int n);/*private ctor*/
 static A * instance;
public:
 static A* getInstance(int m);
 int getm()
 {
 return m;
 }
};
A* A::instance=0;
A::A(int n):m(n)
{ 
}
A* A::getInstance(int m)
{
 if(instance == 0)
 {
 instance = new A(m);
 } 
 return instance;
}
int main()
{
 A *aptr = A::getInstance(10);
 cout<<aptr->getm();
 A *anotherptr = A::getInstance(20);
 cout<<anotherptr->getm();
}
In this example class A has only a private constructor. So statement of the type A obj; outside of class will not compile because the call can not access the constructor. Instead we are having a static function getInstance() whcih creates a new object dynamically and returns its address.
The code also returns existing pointer if there is already an object of the class. So we can only create one object of this class - it is a singleton class. 

You can get these notes and also programs, quiz on C++ by downloading the app Simplified C++ by Hegdeapps  

Comments

Popular posts from this blog

Find the error in C++ program

This C++ program is not compiling. What do you think is the error with the program? #include<iostream> using namespace std; int main() {    int arr[10];    arr={1,2,3,4,5,6,7,8};    cout<<"arr[0]="<<arr[0];    return 0; } Is the error due to Not using printf Initialising the array with only 8 elements instead of 10 Initialising array in the next statement instead of in definition. None of the above  Now if you like this question, there are plenty more questions like this and programs and notes in my app Simplified C++. Download the Simplif ied C++   by Hegdeapps now By the way the correct answer is (3)

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...

MemoryAce for sharper mind

Remembering faces : We tend to forget faces and their names - unlike you have an excellent memory. MemoryAce app shows you some faces for few seconds and then shows the list with one face missing you need to identify the missing face. To avoid any problems with privacy laws, I have used all faces from Simpsons TV serial. So if you need an app to keep your mind and memory sharp, you must download the MemoryAce app from Hegdeapps .