Class Method with Class Variables – Bad Idea?

cclass-designencapsulationmethodsobject-oriented

Here's what I mean:

class MyClass {
    int arr1[100];
    int arr2[100];
    int len = 100;

    void add(int* x1, int* x2, int size) {
        for (int i = 0; i < size; i++) {
            x1[i] += x2[i];
        }
    }
};

int main() {
    MyClass myInstance;

    // Fill the arrays...

    myInstance.add(myInstance.arr1, myInstance.arr2, myInstance.len);
}

add can already access all of the variables that it needs, since it's a class method, so is this a bad idea? Are there reasons why I should or should not do this?

Best Answer

There are may things with the class that I would do differently, but to answer the direct question, my answer would be

yes, it is a bad idea

My main reason for this is that you have no control over what is passed to the add function. Sure you hope it is one of the member arrays, but what happens if someone passes in a different array that has a smaller size than 100, or you pass in a length greater than 100?

What happens is that you have created the the possibility of a buffer overrun. And that is a bad thing all around.

To answer some more (to me) obvious questions:

  1. You are mixing C style arrays with C++. I am no C++ guru, but I do know that C++ has better (safer) ways of handling arrays

  2. If the class already has the member variables, why do you need to pass them in? This is more of architectural question.

Other people with more C++ experience (I stopped using it 10 or 15 years ago) may have more eloquent ways of explaining the issues, and will probably come up with more issues as well.

Related Topic