Sunday 8 July 2018

Named Constructor

By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ?
Answer : Yes, Constructor can be defined in private section of class




Named Constructor Idiom : Since constructor has same name as of class, different constructors are differentiated by their parameter list, but if numbers of constructors is more, then implementation can become error prone.
With the Named Constructor Idiom, you declare all the class’s constructors in the private or protected sections, and then for accessing objects of class, you create public static functions.
For example, consider below CPP program

using namespace std;
class Point
{
    public:
     
    // Rectangular coordinates
    Point(float x, float y);    
     
    // Polar coordinates (radius and angle)
    Point(float r, float a);    
     
    // error: ‘Point::Point(float, float)’ cannot
    // be overloaded
};
int main()
{
    // Ambiguous: Which constructor to be called ?
    Point p = Point(5.7, 1.2);
    return 0;
}
This problem can be resolved by Named Constructor Idiom. The above CPP program can be improved as following :
// CPP program to demonstrate
// named constructor idiom
#include
#include
using namespace std;
class Point
{
    private:
    float x1, y1;
    Point(float x, float y)
    {
        x1 = x;
        y1 = y;
    };
public:
    // polar(radius, angle)
    static Point Polar(float, float);
     
    // rectangular(x, y)
    static Point Rectangular(float, float);
    void display();
};
 
// utility function for displaying of coordinates
void Point :: display()
{
    cout << "x :: " << this->x1 <
    cout << "y :: " << this->y1 <
}
 
// return polar coordinates
Point Point :: Polar(float x, float y)
{
    return Point(x*cos(y), x*sin(y));
}
 
// return rectangular coordinates
Point Point :: Rectangular(float x, float y)
{
    return Point(x,y);
}
int main()
{
    // Polar coordinates
    Point pp = Point::Polar(5.7, 1.2);
    cout << "polar coordinates \n";
    pp.display();
     
    // rectangular coordinates
    Point pr = Point::Rectangular(5.7,1.2);
    cout << "rectangular coordinates \n";
    pr.display();
    return 0;
}
Output :
polar coordinates 
x :: 2.06544
y :: 5.31262
rectangular coordinates 
x :: 5.7
y :: 1.2

No comments:

Post a Comment