2

I have the following class declared :

class MyVector {

  private:
    int           *data;
    unsigned int  vector_size;

  public:
    MyVector();
    MyVector(unsigned int n);
    MyVector(unsigned int size, int *in_array=NULL);
    MyVector(const MyVector& copy);
    ~MyVector();
    void print();

    // Assignment operator.
    MyVector& operator=(const MyVector& v);
};

// Implementing operator overloading.

MyVector& operator*(const int &lhs, const MyVector &rhs);

MyVector& operator*(const MyVector &lhs, const MyVector &rhs);

I wish to implement an overloaded operator (*) so that I can use to multiply the objects of this class with a scalar (on the left hand side) or another object of the same type.

So, in execution, something like this :

// If all c, a, and b are of type MyVector.

c = (a * b);

And

// If c is of type MyVector.

c = (5 * c);

In implementation however I know I cannot access the private members of the class in this way. An alternative would be to use the friend keyword, but wouldn't that be abusing its usage ?

If it helps, this is my implementation of one of the overloaded functions (scalar multiplication) :

MyVector& MyVector::operator*(const int &lhs, const MyVector &rhs) {

    for (unsigned int i = 0; i < rhs.vector_size; i++) {
        rhs.data[i] = rhs.data[i] * lhs;
    }

    return *rhs;
}
Objective-J
  • 319
  • 1
  • 2
  • 13
  • The signature should be `MyVector MyVector::operator*(const int &lhs, const MyVector &rhs)` and you need a temporary instance of `MyVector` to create the result. – πάντα ῥεῖ May 06 '16 at 00:29
  • 2
    You should return by value. `operator*` does not modify its operands. One option would be to implement `operator*=`, and make `operator*` call that. – M.M May 06 '16 at 00:30
  • Your existing implementation fails to compile because you implicitly convert const reference to non-const. Also it is a logical error to modify `rhs.data[i]` since `rhs` is const. And `operator*` is not even a member function of `MyVector`. – M.M May 06 '16 at 00:31
  • @πάνταῥεῖ Your signature will yield the `must take either zero or one argument` error. – Objective-J May 06 '16 at 00:36
  • @Objective-J Sorry, it's not a member of course, also the scalar needs to go at the right side: `MyVector operator*(const MyVector &rhs, const int &lhs)` – πάντα ῥεῖ May 06 '16 at 00:39
  • @πάνταῥεῖ That case doesn't work either. I guess I'll have to force usage of the `friend` keyword. – Objective-J May 06 '16 at 00:47
  • @Objective-J Well, the dupe explains everything you need to know. I'm not going to play that _"fix my incomplete code plz"_ game with you. – πάντα ῥεῖ May 06 '16 at 00:50
  • @πάνταῥεῖ Alright, I'll take a look. Thanks. – Objective-J May 06 '16 at 00:50
  • @Objective-J don't use friend.. use `operator*=` delegation (as shown in examples on the linked thread) – M.M May 06 '16 at 03:18

0 Answers0