Wednesday, 25 March 2015

Static members in C++

Explain Static members in Cpp with examples:

To avoid the global variables in C, there is concept called static members are introduced in C++.

Why we need Static Variables and Static members?

1. The static variables or members are used to avoid the data modification and the name clashing with the other variables.
2. Using the static data we can allocate single storage space to be used by all objects of a class.
3. There is a single piece of storage for a static data member, regardless of how many objects of that class you create.
4. If the member variable is created as a static, all the related objects of that class can communicate with each other and can share the same static storage space.

What is the scope of the static variable?

The scope of the static variable is inside the class, and we can declare the static member as public, private or protected.


Who will allocate memory for the static variables?

So we need to define the static variable outside the class, commonly we need to place it in the implementation file (.CPP).Because, the compiler will not allocate storage for you. The linker will report an error if a static data member is declared but not defined. And here no in lining is allowed

Let us see the simple example, if you create a static data member inside a class like this:
class TestClass {
static int iVal;
public:
//our own declarations
};


We need to provide the storage space for that like below
int TestCalss::iVal = 10;


We must initialize the static variable using the scope resolution operator and the class name are used to specify TestClass::iVal.

So we may get the doubt that the static variables break the protection mechanism?
The answer is No, It’s a completely safe practice for two reasons.

First, the only place this initialization is legal is in the definition. Indeed, if the static data were an object with a constructor, you would call the constructor instead of using the = operator. Second, once the definition has been made, the end-user cannot make a second definition – the linker will report an error. And the class creator is forced to create the definition or the code won’t link during testing. This ensures that the definition happens only once and that it’s in the hands of the class creator.

See the complete example
#include "stdafx.h"
#include <iostream>
using namespace std;
int iValX = 100;
class StaticTest
{
static int iValX;
static int iValY;
public:
  void Dump () const
  {
    cout << "StaticTest::iValX = " << iValX << endl;
    cout << "StaticTest::iValY = " << iValY << endl;
  }
};
int StaticTest::iValX = 1;
int StaticTest::iValY = iValX + 1;
int main ()
{
  StaticTest ocTest;
  ocTest.Dump ();
    getchar ();
    return 0;
}
The output of the above program is:
StaticTest::iValX = 1

StaticTest::iValY = 2


Here, the qualification WithStatic:: extends the scope of WithStatic to the entire definition.

No comments: