2

I've never used operator overloading before and on one of my assignments it says:

"Use polymorphism only as appropriate. The general rule is that if an inbuilt operator matches the purpose of a member function then it should be overloaded."

I've managed to get both versions to work and I think that the 2nd version of ApplyFilter is better. but by me using operator overloading does it make the code a bit harder to read?

Non-Overloaded

int TheFilter::ApplyFilter(TheData& dataIn, TheData& dataOut) {
    // other stuff here.
    for (int i = 0; i < dataOut.length(); i++) {
        dataOut.set_values(i, 0);
        for (int j = 0; j < length(); j++) {
            dataOut.set_values(i, ( dataOut.get_values(i) 
                           + (dataIn.get_values(i+j) * get_values(j)) ));
        }
    }
}

Overloaded

int TheFilter::ApplyFilter(const TheData& dataIn, TheData& dataOut) {
    // other stuff here
    for (int i = 0; i < dataOut.length(); i++) {
        dataOut[i] = 0;
        for (int j = 0; j < length(); j++) {
            dataOut[i] += dataIn[i+j] * values[j];
        }
    }
    return OK;
}

EDIT - The Data Class that I was using for the overloaded version!

class TheData {
    public:
        int length()
        double& operator[] (int index);
        const double& operator[] (int index) const;
        void print();
        void resize(int);

    private:
        std::vector<double> values;
        bool valid;
};
slasher53
  • 141
  • 1
  • 7
  • 2
    This depends on `data` class... – yizzlez Feb 05 '14 at 18:30
  • Here are the basic rules for operator overload is in C++? [Basic Rules Of Overloading Operators](http://stackoverflow.com/questions/4421706/operator-overloading/4421708#4421708) – Moonhead Feb 05 '14 at 18:33

1 Answers1

0

The Overloaded version is more clean and intuitive. The non-overloaded is more verbose. I do not think there is, really, a "right way", for this stuff. I would do the overloaded version in a C++ program, though.

ThunderGr
  • 2,297
  • 29
  • 20