Iowa15
Iowa15

Reputation: 3079

How to create an operator that copies one array to another in c++

I need to create an operator that will copy the contents in one array to another. A.K.A an equal operator. I am thinking something along these lines:

    operator=(string array[10][10], string array2[10][10])
    {
        int row = 0; int column = 0;
        for(column=0; column<=9; column++)
        {
            for(row=0; row<=9; row++){
                array2[row][column]=array[row][column];
            }
        }
    }

I am just not sure on the syntax of operator declarations which is my problem. I know how to make the inside code even if I got the code displayed above wrong. I am just not sure how to write the "operator=(string ....)"

Upvotes: 1

Views: 132

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133072

You can't. For two reasons

  • An array is a built in type, operator overloading is allowed only if at least one of the arguments is a user-defined type
  • operator = is one of the 4 operators (along with [], (), and ->) that have to be members of the class that they are overloaded for1. An array is not a class.

What you can do is

  • Have a named function instead of operator

  • wrap the array into a class

  • use vector<vector<string> > which already has the assignment (<-- my vote goes here)

1As to why these have to be members, you can see this question of mine: Rationale of enforcing some operators to be members

Upvotes: 9

templatetypedef
templatetypedef

Reputation: 372982

You cannot overload operators in C++ unless one of the arguments is of class type (or the operator is a template). This makes sense, because otherwise you could do Crazy Things like redefining the built-in + operator on integers to do subtraction:

int operator+ (int lhs, int rhs) { // Not legal
    return lhs - rhs; // Whoops!
}

In the case of what you're doing, you're trying to redefine what operator = means on arrays, which is not allowed. Moreover, it's not a good idea, because if it were to succeed it would violate the Principle of Least Surprise, since you would make code like this that is normally illegal suddenly compile:

string array[10][10], string array2[10][10];
array = array2; // Problem; this isn't legal C++ code!

If you want to support array deep-copying, you will need to write your own function to do this that isn't an overloaded assignment operator. Alternatively, and probably a much better idea, you should consider wrapping the arrays in either a class or a struct. You could then overload operator = on that class or struct to do the deep copy. On top of this, you would get the added benefit that you could prevent people from accessing the arrays at invalid indices, since you could define getters and setters that would check the index.

Hope this helps!

Upvotes: 1

Related Questions