Python: default values in a dictionary

2 Comments

Sometimes it’s useful to define an associative array which maps a certain key to a list of elements. This is used basically everywhere you need to achieve some categorization. Just to give an example, suppose we want to group a bunch of people by name. Each person has an unique id, while there may be multiple guys with the same name.

More

Comparison

Leave a comment

As you probably know, in C++ there’s a standard way of implementing a comparison semantics for two objects, and this is achieved by means of the operator overloading.

The following is a valid program:

#include 

struct Foo
{
    int x;
    void test() const {
        std::cout << "test: " << x << std::endl;
    }
    bool operator== (const Foo &other)
    {
        test();
        return x == other.x;
    }
};

int main ()
{
    Foo f, g;
    f.x = 3;
    g.x = 4;
    std::cout << "Eq1: " << (f == g) << std::endl;
    std::cout << "Eq2: " << (g == f) << std::endl;
    return 0;
}

The output of the program will be:

test: 3
Eq1: 1
test: 4
Eq2: 1

Now, did you ever try to print something with the std::cout stream? Provided we include the fstream header, we can write the following code:

std::ostream & operator<< (std::ostream &o, const Foo f)
{
    return (o << "Foo instance with x=" << f.x);
}

which allows us to write something like:

Foo f = {3};
std::cout << f << std::endl;

thus obtaining the following output:

Foo instance with x=3

This is good because, in principle, we cannot modify the fstream class adding a method for newly defined type Foo. So far I asked myself: can I do the same thing with arbitrary operators?

I removed the method bool Foo::operator== (const Foo &other) from the Foo struct, and added the following code:

bool operator== (const Foo &f0, const Foo &f1)
{
    return f0.x == f1.x;
}

…and this works! Nice!

The following question is: what if I define both the bool Foo::operator== (const Foo &other) method and the bool operator== (const Foo &f0, const Foo &f1) function?

It turns out the compiler likes best the class-defined method. This is pretty reasonable, since gives the developer a better control of the defined class, while externally defined behaviors get honoured only if no behavior is provided.

Follow

Get every new post delivered to your Inbox.