Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling constructor with multiple arguments

I have

Triangle::Triangle()
{
    A = NULL;
    B = NULL;
    C = NULL;
}
Triangle::Triangle(Point& X,Point& Y, Point& Z)
{
    A = new Point;
    *A = X;
    B = new Point;
    *B = Y;
    C = new Point;
    *C = Z;
}

and 

istream& operator>>(istream& in, Triangle& T)
{
    Point X,Y,Z;
    in>>X>>Y>>Z;
    Triangle T(X,Y,Z);  
    return in;
}

Where Point is another class which defines a point with coordonates X and Y. I don't know how to call the constructor with multiple arguments in the overloaded function. Can you help me?

like image 471
user2116010 Avatar asked Oct 22 '22 16:10

user2116010


1 Answers

This is how you do it:

Point px;
Point py;
Point pz;
Triangle trig(px, py, pz);

trig will be the object, which is an instance of class Triangle and the above would call the constructor with 3 Point arguments.

Another way is for pointers:

 Triangle *pTrig = new Triangle(pX, pY, pZ);

In addition, I suggest, that this would be better:

Triangle::Triangle()
   : A(NULL), B(NULL), C(NULL)
{
}

Triangle::Triangle(const Point& X,const Point& Y, const Point& Z)
 : A(new Point(X)), B(new Point(Y)), C(new Point(Z))
{
}

Assuming that Point has a copy constructor.

You want to call it from inside the operator>> function to update argument T, but this won't work, because you cannot call the constructor on something that's already constructed. Instead, what you need is to implement an assignment operator. Please see http://en.wikipedia.org/wiki/Assignment_operator_%28C%2B%2B%29 for more information.

Then you can do T = Triangle(X,Y,Z);

To implement the assignment operator, you can do this:

Triangle& Triangle::operator= (const Triangle& other)
{
    if (this != &other) // protect against invalid self-assignment
    {
        if (A != NULL) delete A;
        if (B != NULL) delete B;
        if (C != NULL) delete C;
        A = new Point(other.A);
        B = new Point(other.B);
        C = new Point(other.C);
    }
    return *this;
}

Assuming Point has copy constructors. To implement copy constructors, please see http://en.wikipedia.org/wiki/Copy_constructor

A copy constructor looks like the following, but you need to do it for Point:

Triangle& Triangle::Triangle(const Triangle& other)
  : A(new Point(other.A)), B(new Point(other.B)), C(new Point(other.C))
{
}
}
like image 156
ruben2020 Avatar answered Oct 27 '22 09:10

ruben2020