Non const field fine in a function but recognised as const in another one

Viewed 61

I have a non const field ctxt. And I have a funtion like this:

inventory_input inventory_selector::get_input()
{
    inventory_input res;

    const input_context ip;

    res.action = ctxt.handle_input();
    res.ch = ctxt.get_raw_input().get_first_input();

    std::tuple<point, bool> tuple = ctxt.get_coordinates_inventory( w_inv );//Fine
    std::tuple<point, bool> tuple = ip.get_coordinates_inventory( w_inv );//Error

    res.entry = find_entry_by_invlet( res.ch );

    if( res.entry != nullptr && !res.entry->is_selectable() ) {
        res.entry = nullptr;
    }

    return res;
}

the error is "the object has type qualifiers that are not compatible with the member function" as ip is const but the funtion get_coordinates_inventory is not const. However, I have a nother funtion like this:

inventory_entry *inventory_selector::find_entry_by_coordinate( point coordinate ) const
{
    input_context ip;
    std::tuple<point, bool> tuple = ctxt.get_coordinates_inventory( w_inv );//surprising, this line is having error.
    std::tuple<point, bool> tuple = ip.get_coordinates_inventory( w_inv );//this line dosn't has error
}

The error message is: the object has type qualifiers that are not compatible with the member function "input_context_inventory" object type is: const input_context. I cannot understand why is this happening, both ctxt and ip are non const how can one of them having error while another one doesn't?

1 Answers

I have a non const field ctxt

...

the funtion get_coordinates_inventory is not const

There is your problem. Note the const qualifier on this method:

inventory_entry *inventory_selector::find_entry_by_coordinate( point coordinate ) const
                                                                                  ^^^^^

This means that this method can be invoked on a const inventory_selector. Therefore, within this function the implicit this pointer points to const inventory_selector. Because of this, you can't invoke a non-const method on ctxt -- it is also const since it is a member of an object that is considered const within the context of the method:

  • this is const inventory_selector *.
  • So this->ctxt is const input_context &.
  • So the invocation this->ctxt.get_coordinates_inventory() is disallowed because that method is not declared const.

Either inventory_selector::find_entry_by_coordinate should be made non-const, or input_context::get_coordinates_inventory should be made const.

Related