Please refer to rule #41 of C++ Coding Standards or Sutter's Gotw #70, which states that:
Make data members private, except in behaviorless aggregates (C-style structs).
I often would like to to add a simple constructor to these C-style structs, for the sake of convenience. For example:
struct Position
{
Position(double lat=0.0, double lon=0.0) : latitude(lat), longitude(lon) {}
double latitude;
double longitude;
};
void travelTo(Position pos) {...}
main()
{
travelTo(Position(12.34, 56.78));
}
While making it easier to construct a Position on the fly, the constructor also kindly zero-initializes default Position objects for me.
Maybe I can follow std::pair's example and provide a "makePosition" free function? NRVO should make it as fast as the constructor, right?
Position makePosition(double lat, double lon)
{
Position p;
p.latitude = lat;
p.longitude = lon;
return p;
}
travelTo(makePosition(12.34, 56.78));
Am I going against the spirit of the "behaviorless aggregate" concept by adding that measly little constructor?
EDIT:
Yes, I was aware of Position p={12.34, 56.78}
. But I can't do travelTo({12.34, 56.78})
with pure C structs.
EDIT 2:
For those curious about POD types: What are POD types in C++?
FOLLOW-UP: I've asked a follow-up question here that is closely related to this one.