Re: Why can't PODs have constructors?
"BobR" <removeBadBobR@worldnet.att.net> wrote in message
news:yG8qi.4763$ax1.3539@bgtnsc05-news.ops.worldnet.att.net...
JohnQ <johnqREMOVETHISprogrammer@yahoo.com> wrote in message...
There must be something at the implementation level that makes the
standard
disallow constructors in PODs (?). What is that? Don't most
implementations
just break out the constructor member functions into construct_obj_x
non-member functions taking a 'this' ptr?
PODs do have Ctor, copy-Ctor, and assignment operators. Otherwise you
would
not be able to use them in std containers (like std::vector). You just
can't
write your own and keep it a POD ('C'). (IMHO.)
It sure would be convenient to initialize structs with constructors and
still having them be PODs.
John
A little extra step can do that.
This uses a 'RECT' from windows. It's a POD 'C' struct with 4 longs.
Try this with your own POD struct.
struct MyRect : public virtual RECT{
Why the virtual inheritance?
MyRect( long x1 = 0, long y1 = 0, long x2 = 10, long y2 = 10 ){
Defining all the default args will lead to ambiguity errors being produced
by the compiler.
left = x1; // init the RECT members
bottom = y1;
right = x2;
top = y2;
}
~MyRect(){ this->RECT::~RECT();}
Ooo, that destructor doesn't look good at all there the way you defined it.
(Wouldn't be allowed in a POD either).
RECT Rect(){ return *this;}
You were _trying_ to define a conversion operator, but you don't have to
because MyRect IS a RECT. If you were to embed the RECT into MyRect instead
of derive from it, then you'd need a conversion operator. Currently I'm
doing the derivation from RECT rather than composition (embedding) with
RECT, but it escapes me why I decided that in this case derivation was
better than composition (probably so I don't have to provide accessor
functions and the conversion operator)..
};
That's kind of what I've been doing to get compatibility of MyRect and RECT
(I do something a little different, but for practical discussion, it
suffices to say that). But it doesn't solve the problem since you can't
create an array of MyRects and get the desired layout (a contiguous array of
16-byte RECT-like things). It should be possible to define a MyRect so that
it is 16-bytes and still allows initializing constructors.
Of course it would take something a little more complex to justify the
extra
layer, or you would just do:
RECT rect2 = { 14, 19, 25, 55};
Well consider that you might want to construct a MyRect with 2 MyPoint
objects:
MyRect(MyPoint& origin, MyPoint& extent);
MyRect will (again/still) not FORMALLY be a POD if you define the above
constructor.
John