arithmetic operators overloading for class with pointer

I am stucked in a problem of overloading arithmetic operators such as "+,*" for a class in the form
1
2
3
4
5
class Point
{
    int     N;   //  dimension of the point
    double *Pos; //  length of N
}


My assign operator is :
1
2
3
4
5
6
7
Point& Point::operator= (const Point& pt)
{
    N= pt.N;
    if(Pos == NULL) Pos = new double[N];
    memcpy(Pos, pt.Pos, N*sizeof(double));
    return *this;
}


operator for multiplication by a double constant "*" is:
1
2
3
4
5
6
Point operator*( double alpha, const Point& pt )
{
    Point ptr = Point(pt);  // this is a constructor
    for (int i=0; i<pt.N;i++)  ptr.Pos[i] *= alpha;
    return ptr;
}


the add operator "+" is:
1
2
3
4
5
6
Point operator+( const Point& pt1, const Point& pt2 )
{
    Point ptr = Point(pt); // this is a constructor
    for (int i=0; i<pt1.N; i++)  ptr.Pos[i] += pt2.Pos[i];
    return ptr;
}


Based on the above overloading, What I am going to do is :

 
P = alpha*P1 + beta*P2;  // alpha and beta are double constants, P1 and P2 are Points objes 


It is ok with Intel C++ 14.0 compiler, but does not work with the microsoft visual c++ 2012 compiler in debug mode in visual studio 2012.

I stepped in those operators and found that visual c++ compiler deconstructs the ptr in operators "*" and "+" before its return while intel c++ finished the operation P = alpha*P1 + beta*P2; and delete those ptrs at last.

Portability of my operator overloading is worse. I appreciate if anyone can help me with those arithmetic operators overloading for class with pointers in it.
Thanks in advance!
Last edited on
Can you post the code to reproduce the problem?

but does not work with the microsoft visual c++ 2012 compiler
The'd make the compiler unusable

I stepped in those operators and found that visual c++ compiler deconstructs the ptr in operators "*" and "+" before its return while intel c++ finished the operation P = alpha*P1 + beta*P2; and delete those ptrs at last.
That's not a problem. The variable is destructed after the value is copied to another [temporary] variable.
> Point ptr = Point(pt); // this is a constructor
perhaps you should have showed your copy constructor then.
Also, if you are going to copy the arguments, then you could simply ask for a copy instead of a reference.

your 'operator=' is ill-formed for self-assignment

Last edited on
Your code assumes that N is the same for both points.
Topic archived. No new replies allowed.