Wednesday, 25 March 2015

Static array initialization In C++ with examples

Static array initialization In Cpp with examples:

we have seen that <give the link to the Static members in C++> static variable<link end> how we have to define inside a class body. Like that it is also possible to create arrays of static objects, both const and non-const.

see the below syntax:

class ClasValues
{
  static const int scSize = 100;
  static const long scLong = 100;
  static const int stCVal[];
  static const long stLVal[];
  static const float stfVal[];
  static const char stcVal[];
  static int iSize;
  static const float scFloat;
  static float stcTable[];
  static char stChars[];
};
int ClasValues::iSize = 100;
const float ClasValues::scFloat = 10.1;
const int ClasValues::stCVal[] = { 99, 47, 33, 11, 7 };
const long ClasValues::stLVal[] = { 99, 47, 33, 11, 7 };
const float ClasValues::stfVal[] = { 1.1, 2.2, 3.3, 4.4 };
const char ClasValues::stcVal[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
float ClasValues::stcTable[4] = { 1.1, 2.2, 3.3, 4.4 };
char ClasValues::stChars[10] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' };
 int main ()
{
  ClasValues ocVal;
   getchar ();
  return 0;
}

With static constants of integral types you can provide the definitions inside the class.
It is also possible to create static const objects of class types and arrays of such objects.

Let us see the simple code that helps us to understand how to implement and use the static arrays and the static objects.

class ClassX {
int m_iVal;
public:
  ClassX(int iVal) : m_iVal (iVal) {}
};
class StatTest
{
  static ClassX ocsObj2;
  static ClassX xTable2[];
  static const ClassX ocsObj3;
  static const ClassX xTable3[];
};
ClassX StatTest::ocsObj2 (20);
ClassX StatTest::xTable2[] = { ClassX (1), ClassX (2), ClassX (3), ClassX (4) };
const ClassX StatTest::ocsObj3(40);
const ClassX StatTest::xTable3[] = { ClassX(1), ClassX(2), ClassX(3), ClassX(4) };
int main ()
{
  StatTest ocObj;
  getchar ();
  return 0;
}


The initialization of both const and non-const static arrays of class objects must be performed the same way.

No comments: