Thursday, June 9, 2011

How to Initialize const member variable? or What is Initialization Lists?

In C++, Memory will be allocated for all member variables of a class even before the constructor of that class is getting called. So we can't initialize a const member variable inside a class constructor.

It can be initialized as in the below example using initialization list.


// Sample.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <conio.h>


using namespace std;

class CTriangle
{
public:
CTriangle();
const float m_fPi;
};
CTriangle::CTriangle():m_fPi(3.14)
{
//constructor
}
int main()
{
CTriangle obj;
cout<<obj.m_fPi;

getch();
return 0;
}