1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

"Named Constructor Idiom"?

Discussion in 'C++' started by heena.mca, Mar 13, 2008.

  1. heena.mca

    heena.mca New Member

    Joined:
    Feb 14, 2008
    Messages:
    20
    Likes Received:
    0
    Trophy Points:
    0
    can some body please tell me What is the "Named Constructor Idiom"?
     
  2. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA
    Make all constructor in private or protected member and provide a static member function as a public member.
    ( Reason is to make error less because constructor may have a lot of costructor, may conflict to other)

    Code:
    
    class Point {
        public:
          Point(float x, float y);     // Rectangular coordinates
          Point(float r, float a);     // Polar coordinates (radius and angle)
          // ERROR: Overload is Ambiguous: Point::Point(float,float)
        };
    
        int main()
        {
          Point p = Point(5.7, 1.2);   // Ambiguous: Which coordinate system?
        }
    
    One way to solve this ambiguity is to use the Named Constructor Idiom:
    
        #include <math.h>              // To get sin() and cos()
    
        class Point {
        public:
          static Point rectangular(float x, float y);      // Rectangular coord's
          static Point polar(float radius, float angle);   // Polar coordinates
          // These static methods are the so-called "named constructors"
          // ...
        private:
          Point(float x, float y);     // Rectangular coordinates
          float x_, y_;
        };
    

    detail you can see http://www.faqs.org/faqs/C++-faq/part4/
     

Share This Page