Saturday, June 6, 2015

const data members in C++

1. Constant member of an Object:
the constant member gets initialized in the initialization list:

class A
{
  A(
int size);  // 
  const int SIZE ;  
};
A::A(
int size) : SIZE(size)  
{

}
A  a(
100); // value of SIZE in object a is : 100
A  b(200); // value of SIZE in object a is : 200 

The whole idea for a constant is that you can initialize it but you cannot change it.

2. Const member of a Class:
2.1 using enum (int only)
class A
{
  
enum { SIZE1 = 100, SIZE2 = 200}; // enum const member
  int array1[SIZE1];
  
int array2[SIZE2];
}; 

2.2 using static

class A
{

  static const int a = 100;
  static const pi = 3.1415926;

}; 



No comments: