Search code examples
c++classoopoperator-overloadingencapsulation

Overloading operator in class and returning reference to private value


Example class I'm using:

class Vector
{
double val[3];
public:
double & operator [] (const unsigned int & index) {return this->val[index];};
}

Then I call it like:

Vector Example;
Example[0]=5;

Is using operator overloading like this correct or it is against encapsulation and I should use something different? I'm using reference to private value here and I'm not sure about this implementation.


Solution

  • This is a leak in your abstraction. It exposes the fact you have actual doubles that can be read from or written to.

    If you later wanted to change those doubles into a remote immediate network connection data or stored in a database, you would be forced to add breaking changes to your interface.

    That being said:

    It is worth it. You probably will never modify this type to do something that insane, and there are significant compile, design and runtime overheads to unlimited abstraction.

    Abstraction and encapsulation serve a purpose and have a cost.

    std::vector<bool>'s operator[] is an example of what you can do when reference return types are not ok. There it is used to return sub-byte elements. Note that it is widely considered a design error.