1

I want to overload equal to "=" operator in C++ for

class Array
{
    int *p;
    int len;
};

All functions/constructor etc. are defined.

My question: Could someone give me the prototype of the operator overloaded function? And suppose:

Array a,b;
b=a;

Which of "a" and "b" would be passed implicitly and which explicitly?

Thanks in advance.

Marco A.
  • 43,032
  • 26
  • 132
  • 246
Raghav Sharma
  • 109
  • 1
  • 1
  • 6

3 Answers3

1

The prototype is Array& operator=(const Array& that).

While implementing this, remember about the rule of three and make good use of the copy-and-swap idiom.

mp_
  • 705
  • 3
  • 7
0

There is probably more than one way to do it, but here is an option.

Public Functions:

Array::Array(const Array& array)
{
    Allocate(0);
    *this = array;
}

Array::~Array()
{
    Deallocate();
}

const Array& Array::operator=(const Array& array)
{
    if (this == &array)
        return *this;

    Deallocate();
    Allocate(array.len);

    for (int i=0; i<len; i++)
        p[i] = array.p[i];

    return *this;
}

Non-Public Functions:

void Array::Allocate(int size)
{
    len = size;
    if (len > 0)
        p = new int[len];
}

void Array::Deallocate()
{
    if (len > 0)
        delete[] p;
    len = 0;
}

Of course, you can always use a vector<int> instead...

barak manos
  • 29,648
  • 10
  • 62
  • 114
0

You're looking for the assignment operator = (not equal-to, which is operator== and usually serves as an equality comparison)

class Array
{
    int *p;
    int len;

public:
    // Assignment operator, remember that there's an implicit 'this' parameter
    Array& operator=(const Array& array)
    {
        // Do whatever you want
        std::cout << "assignment called";

        return *this;
    }
};


int main(void) {

    Array a, b;

    a = b;
}

remember that since you wrote "All functions/constructor etc. are defined" you should pay attention to what you need your class to do and possibly also implement destructor as in the rule of three (and/or take a look at its variants in C++11, might be relevant since there's no other code posted).

Marco A.
  • 43,032
  • 26
  • 132
  • 246