Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   "Named Constructor Idiom"? (http://www.go4expert.com/forums/named-constructor-idiom-t9309/)

heena.mca 13Mar2008 15:54

"Named Constructor Idiom"?
 
can some body please tell me What is the "Named Constructor Idiom"?

asadullah.ansari 13Mar2008 17:03

Re: "Named Constructor Idiom"?
 
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: cpp

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/


All times are GMT +5.5. The time now is 07:39.