Wednesday, August 30, 2017

May the CONST be with you

In C++, 'const' is a important keyword to avoid bugs.

Declaring item of some kind of game, it will be like this.

class Item
{
    int _count;
    std::string _name;

public:
    Item(std::string const& name, int count)
    :_name(name), _count(count) {}
    
    std::string const& Name() {
        return _name;
    }
    int Count() {
        return _count;
    }
};

And let's implement a function for print Item.

// take reference to avoid copying object, and set const to avoid modifying that.
void PrintItem(Item const& item)
{
    std::cout << "name: " << item.Name() << " count:" << item.Count();
}
This is good idea to set 'const' for read-only reference. It prevents to modify data unintendedly. But the code above gets compile-time error.
error: passing 'const Item' as 'this' argument of 'const string& Item::Name()' discards qualifiers [-fpermissive]
error: passing 'const Item' as 'this' argument of 'int Item::Count()' discards qualifiers [-fpermissive]
Compiler says calling Item::Name() and Item::Count() may modify the internal data of Item. We humans know the Item::Name() and Item::Count() never modify data, but compiler doesn't. So we need to tell the compiler that Item::Name() and Item::Count() does not modify data like this.
class Item
{
    int _count;
    std::string _name;

public:
    Item(std::string const& name, int count)
    :_name(name), _count(count) {}
    
    std::string const& Name() const {   // 'const' after function name tells the function never modify internal data.
        return _name;
    }
    int Count() const {   // The same to above.
        return _count;
    }
};

Now we can compile and call the PrintItem() function.

What if a function declared as 'const' modifies internal data?
It gets compile-time error too.




No comments:

Post a Comment

It&#39;s magic! std::bind

'std::bind' is a powerful helper for working around 'std::function'. 'std::bind' makes a instance of 'std::fun...