-
Non-static const
Can i not declare a non-static const data member?
Code:
class A
{
public:
const int x;
A()
{
x = 10;
}
};
int main()
{
return 0;
}
problem is here is, compiler allows me to declare a non-static const data member, meaning i can somehow use it. But how do i initialize it?
Constructor Initialization fails bcoz compiler prevents assignment to a const data member,
and initialization at declaration is prevented by ISO C++ std. that says i cannot initialize data members inside a class until they are static const
so, why even the declaration of non-static const data member has been allowed by the compiler, when there is no way i can initialize it ?
-
I'm not sure but try this is the implementation file:
const int A::x = 10;
-
tried this :-
Code:
class A
{
public:
const int x;
};
const int A::x=10;
int main()
{
return 0;
}
i get this error - ‘const int A::x’ is not a static member of ‘class A’
-
Code:
class A
{
public:
const int x;
A():x(10)
{
}
};
-
Quote:
Originally Posted by
vart
Code:
class A
{
public:
const int x;
A():x(10)
{
}
};
This is the answer you're looking for.
This is why.
-
wow!
initializer list is the only way i could initialize non-static const members
thanx!
-
It is how you should initialize almost all of your nonstatic member variables.