windy401
windy401

Reputation: 197

overloading = operator for self made vector class

I started writing my own vector class and got around to overloading the = operator. I have the code below for something like somevector = someothervector, although I'm not sure it's right, as I'm stuck on making another overload for something like somevector[0] = 5 with which for give my vectors values.

myVector& myVector::operator=(const myVector &obj)
{
    myVector tem(obj.Size()); //make new empty vector of the needed size then fill below

    for (int i = 0; i <= tem.size; ++i)
    {
        tem.array[i] = obj.array[i]; 
    }

    return tem;
}

I have the following for an [] overload which works for reading elements of the vectors but since it's just returning the value of the element, and I'm not sure how to fix that for assignment, I think that may be my main problem.

int myVector::operator[](int ind)
{
    if ( (ind >= 0) && (ind < size) )
    { return array[ind]; }

    return 0;
}

Can some one please offer some advice on this?

Upvotes: 2

Views: 158

Answers (1)

Steve Lorimer
Steve Lorimer

Reputation: 28659

You want to be operating on this, not on a temporary.

That is, you're assigning to the current object's data members

Something along the lines of:

myVector& myVector::operator=(const myVector &obj)
{
    // insert appropriate code here to ensure your array's capacity is sufficient
    // to hold obj.size ints

    size = obj.size;
    for (int i = 0; i < size; ++i)
    {
        array[i] = obj.array[i]; 
    }

    return *this;
}

To enable your requested syntax (somevector[0] = 5) your array subscript operator has to return a reference to the stored object, otherwise you're operating on a temporary. If the index is incorrect you'll probably want to throw an exception if it doesn't exist.

int& myVector::operator[](unsigned ind)
{
    if (ind < size)
        return array[ind];

    throw std::out_of_range("invalid index");
}

Upvotes: 4

Related Questions