Link to home
Start Free TrialLog in
Avatar of arijit_rebaca
arijit_rebaca

asked on

constant in C++,

Hi,
I am not able to find out the reason behind below con snippet
Q1.
Class A
{
public:
 const int a;
};
how can i initilized it within the class and also from a function outside the calss. because
i am getting an error by writing const int a =12; within the class

===========================
Q2. Class A
{
public:
static int const i =10;
};
this is not throughing any compiler error. But the following code is throwing compiler error
Class A
{
static float const i = 12.0;
};

}
}
Avatar of phoffric
phoffric

Q1: > how can i initilized it within the class
You may use a constructor to initialize the constant; e.g., A(int val): a(val) {};

Q1: > how can i initilized it from a function outside the class
Since a is a constant, it is constant at object creation. So you cannot redefine it in a member method.

Q2: > static float const i = 12.0;
Right, it is an error "only static const integral data members can be initialized within a class"
The C++ rule is that integral constant members may be initialized using static const. float is not integral.

I assume you know that "Class" should be "class".
For the float version in Q2, you can do this


class A
{
public:
static float const f;
};

const float A::f = 10;

Open in new window

Avatar of arijit_rebaca

ASKER

hi phoffric,
I know that it will throw error like ""only static const integral data members can be initialized within a class"
but i want to know the reason????
ASKER CERTIFIED SOLUTION
Avatar of pgnatyuk
pgnatyuk
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
"...the value of a const member can be set only at initialization"
it is from:
http://support.microsoft.com/kb/92614
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial