Wednesday, January 16, 2013

Constructor parameters can have the same name as member variables

This just blew my mind today:


#include 

struct Point {
    Point(double x = 0, double y = 0) : x(x), y(y) { }
    double x, y;
    // No destructor needed
};

int main()
{
   Point p(10.0, 5.6);
   std::cout << p.x << " " << p.y << std::endl;
   return 0;
}


Came across the struct definition above when browsing the following link:

http://www.drdobbs.com/cpp/teaching-c-badly-introduce-constructors/229500116

As for the article itself, i'm completely comfortable creating structs with public data members. I try to avoid constructors for these if I intend these to be passed around as message payloads. Creating a constructor destroys the POD-ness of the data structures implying that the structures are copyable, but not assignable.

It also follows that if a structure is going to be used as a message payload, it should not contain pointers or references to other objects outside the structure itself since these can go away, leaving dangling references.

Keeping message payloads POD also has the advantage that these can be passed to C functions / handlers / libraries (though one has to watchout for packing differences there)

If the requirements necessitate a deviation from these (need for a reference or elaborate allocation), then it is absolutely necessary to allocate a constructor, a destructor, a copy constructor, an assignment operator, and r-value versions of the same ("rule of 5")

No comments: