Search code examples
c++templatesoperator-overloadingcoutgeneric-programming

Freaky output: why would this code give any meaningful output, let alone this?


I'm not sure how to even state my question, but here we go...

So, I have this class for which operator[] has an empty body (not yet implemented). Still, when I call it from main(), it produces an output. What's more, the output is exactly what was assigned to it in the previous line.

EDIT: I added a private attribute called emptyValue, and I initialized it to TipVrijednosti() in class constructor.

Here's example:

  template<typename TipKljuca, typename TipVrijednosti>
    class BinStabloMapa : public Mapa<TipKljuca, TipVrijednosti>
    {
            .
            .
        TipVrijednosti &operator[] (const TipKljuca &kljuc) {
            return emptyValue;
        }
        const TipVrijednosti &operator[] (const TipKljuca &kljuc) const {
            return emptyValue;
        }
            .
            .
    }

    int main()
    {
        BinStabloMapa<int, int> m;
        m[100] = 200;
        cout << m[100] << endl;
        return 0;
    }

    OUTPUT: 200

Could anybody tell me why i this happening?


Solution

  • You have undefined behaviour because you're not returning anything from a function that has a non-void return type.

    §6.6.3:

    Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

    §1.3.24:

    undefined behavior
    behavior for which this International Standard imposes no requirements