Pete Becker
10/26/2008 7:22:00 PM
On 2008-10-26 15:18:27 -0400, Pete Becker <pete@versatilecoding.com> said:
> On 2008-10-26 14:53:09 -0400, yuyang08@gmail.com said:
>
>> I have a question on the const methods. If a method is overloaded with
>> a const version, in the case that either one is okay (for example, the
>> following code), which shall the compiler pick? Could you tell which
>> section of the C++ standard specifies this?
>
> It's simply <g> a matter of overload resolution.
>
>> #include <iostream>
>> using namespace std;
>>
>> class A{
>> public:
>> int foo() const { return 6; }
>> int foo() { return 5; }
>> public:
>> int x;
>> };
>>
>> int main()
>> {
>> A ca;
>> int c = ca.foo();
>> cout << "c = " << c << endl;
>> return 0;
>> }
>
> The first version of A::foo takes a this pointer of type const A*; the
> second one takes a this pointer of type A*. At the point of the call,
> ca is not const, so the this pointer that the compiler generates has
> type A*, and the call goes to the second version of A::foo. If that
> version hadn't been defined, the call would go to the remaining (const)
> version after a conversion of the type of the this pointer argument
> from A* to const A*.
Whoops, that's a bit ambiguous. The last sentence should start with "If
that version hadn't been declared," That is:
class A {
public:
int foo() const;
};
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)