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;
};
}
}
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;
};
}
}
For the float version in Q2, you can do this
class A
{
public:
static float const f;
};
const float A::f = 10;
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????
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
"...the value of a const member can be set only at initialization"
it is from:
http://support.microsoft.com/kb/92614
it is from:
http://support.microsoft.com/kb/92614
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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".