Question

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?

Was it helpful?

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

OTHER TIPS

Not such a big puzzle. Your operator [] is returning a reference to some data variable called emptyValue.

            m[100] = 200;

is equivqlent to

            m.emptyValue = 200;

Then you write cout << m[100];

which is just like

            cout << m.emptyValue;

Note: the index '100' is irrelevant.

There is nothing with that :

#include <iostream>
using namespace std;
template<typename TipKljuca, typename TipVrijednosti>
class BinStabloMapa /* : public Mapa<TipKljuca, TipVrijednosti> */ 
//comment inheritance to make it compile, not relevant to the problem
{
    //C++11 syntax, not relevant either
    TipVrijednosti emptyValue=TipVrijednosti();
    public:    
    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; //calls no const operator[], thus emptyValue is changed 
    cout << m[100] << endl; //calls const operator[], thus emptyValue is return
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top