Method overloading with const/non-const variants (was: Re: KDE/kdelibs/kdecore)
Thiago Macieira
thiago at kde.org
Tue Jul 8 13:55:23 BST 2008
Friedrich W. H. Kossebau wrote:
>What about overloaded methods? Hm, running the test from below shows me
> that I have been thinking wrong for many years, duh. So the compiler
> chooses the variant by the constness of the object? I thought it takes
> all possible variants and then narrows the selection further by the
> LHS, going for constness if possible?
>
>Is this defined by the C++ specs? Does anyone know the rationale behind
> this?
Yes, this is defined by the C++ spec. When you call a function foo(...)
with a set of parameters, the compiler will try to find all instances
of "foo" in the class and see which one fits best to the parameters you
gave.
I don't know the exact rules for type promotion and demotion, but there
are cases where it becomes ambiguous. If it does, then the compiler will
print an error and ask you what to do.
An interesting thing about the search is when it happens to template
types: no promotion or demotion is applied. The compiler searches only
for the exact match.
The compiler always selects the less constraining overload of a function
given its CV-qualifiers (CV = const, volatile). If you have the following
four overloads of foo():
void foo();
void foo() const;
void foo() volatile;
void foo() const volatile;
The CV qualifier to a function applies to the this pointer implicit
parameter. So you can think of that as:
void foo(Class *this);
void foo(const Class *this);
void foo(volatile Class *this);
void foo(const volatile Class *this);
So now you can apply the same rules as parameter overloading. That's why
the compiler chooses the less constraining one. That's also why
the "const" variants may be called in any circumstances, but the
non-const ones cannot be called with a const object.
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part.
URL: <http://mail.kde.org/pipermail/kde-core-devel/attachments/20080708/76fac8f0/attachment.sig>
More information about the kde-core-devel
mailing list