The International Simutrans Forum

Development => Technical Documentation => Topic started by: hreintke on November 18, 2012, 11:18:14 AM

Title: Compile trouble
Post by: hreintke on November 18, 2012, 11:18:14 AM
LS,

I am trying to add a function ot fabrik_t and made declation as this


uint32 fabrik_t::get_matched_ausgang (const fabrik_t *fb)


And use it in here


fabrik_t *fab = get_fab( welt, supplier );
if(fab) {
    int w;
    w = get_matched_ausgang (fab);


But get compile error :
'fabrik_t::get_matched_ausgang' : cannot convert 'this' pointer from 'const fabrik_t' to 'fabrik_t &'
1>          Conversion loses qualifiers

Tried several other too, can someone point me to the error I make ?

Herman
Title: Re: Compile trouble
Post by: Dwachs on November 18, 2012, 11:20:09 AM
Maybe you should make get_ausgang const:

uint32 fabrik_t::get_matched_ausgang (const fabrik_t *fb) const
Title: Re: Compile trouble
Post by: hreintke on November 18, 2012, 11:27:04 AM
Dwachs,

Thanks, That worked.
However I don't understand yet enough from const usage why it did. Need some study on that.

Herman
Title: Re: Compile trouble
Post by: Ters on November 18, 2012, 11:40:16 AM
Inside a const method, the object this points to is const. In other words, a const method promises to (and is unable to) modify the object it is called on. If you have a const object, const reference or const pointer, you can only call const methods on it. If you could call non-const methods on it, you would change an object you're not allowed to (and/or have promissed not to) modify.

Though you don't provided much context surrounding your use of get_matched_ausgang, it would seem to me that it is inside another const method (since the error message said this const). Since your inside a method that promises not to change the object it's called on, you can only cause methods that uphold the same promise (by being const).

(There is a legal loophole for modifying parts of an object inside a const method, but that's for very special circumstances. One can also cast away the const, but that's an evil thing to do.)
Title: Re: Compile trouble
Post by: hreintke on November 18, 2012, 11:53:36 AM
Ters,

Thanks, clarifies why it happened and why making it const solved.
My code is within 

void fabrik_t::info_conn(cbuffer_t& buf) const


Herman