Re: Initialization of a const POD member
Pierre Asselin <pa@see.signature.invalid> wrote:
Does the standard preclude classes with const POD members ?
It seems to me there is no way to initialize them.
struct plain_old_data {
int i; short j;
};
class Fred {
const plain_old_data pod;
public:
Fred();
}
Fred::Fred():
pod(42, 22) // error
{}
I have to initialize pod because it is const, but I can't because
it doesn't have a constructor. I can write him a constructor, but
if I did it would no longer be an aggregate (8.5.1) and therefore
not a POD-struct (9, paragraph 4). Am I stuck ?
Not tested but
class PodWrapper
{
plain_pod data; // not const here
public:
PodWrapper(int a,int b)
{
data.i= a;
data.j= b;
}
int i() const {return data.i;}
int j() const {return data.j;}
const plain_pod & pod() const {return data;}
};
now the pod can be read not written, and constructed.
class Fred:PodWrapper // private inheritance
{
public:
Fred(int a,int b):PodWrapper(a,b){}
// ...
};
member functions i(),j(),pod() are have private access in Fred and
the pod can be initialised at construction and only then can it
be written to, if casts are not used.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]