user2116010
user2116010

Reputation: 211

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?

Upvotes: 5

Views: 24935

Answers (2)

ruben2020
ruben2020

Reputation: 1549

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))
{
}
}

Upvotes: 3

Yasser Mohseni
Yasser Mohseni

Reputation: 463

The first two constructors are overrides for default constructor. The third function is operator overloading which overloads >> operator. You just need to create an object of Triangle class as follow:

Triangle tr(x,y,z);

or

Triangle* tr = new Triangle(x,y,z);

Where x, y, and z are objects of Point class.

By the way, as you can see in your operator overloading (the third function), you are already creating an object of class Triangle (Triangle T(X,Y,Z);).

Upvotes: 0

Related Questions