JohnQ said:
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{
MyRect( long x1 = 0, long y1 = 0, long x2 = 10, long y2 = 10 ){
left = x1; // init the RECT members
bottom = y1;
right = x2;
top = y2;
}
~MyRect(){ this->RECT::~RECT();}
RECT Rect(){ return *this;}
};
{ // main or ?
using std::cout; // for NG post
MyRect rect( 10, 12, 22, 42 );
cout<<" MyRect rect.bottom="<< rect.bottom << std::endl;
RECT rect1 = rect.Rect();
cout<<" RECT rect1.bottom="<< rect1.bottom << std::endl;
cout<<" sizeof(rect)="<<sizeof( rect )<<std::endl;
cout<<" sizeof(rect1)="<<sizeof( rect1 )<<std::endl;
}
/* - output -
MyRect rect.bottom=12
RECT rect1.bottom=12
sizeof(rect)=20
sizeof(rect1)=16 // sliced back to POD
// (sixeof long == 4 on my sys)
*/
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};
[ corrections, comments welcome. ]