Boost logo

Boost :

From: Reece Dunn (msclrhd_at_[hidden])
Date: 2004-01-04 07:57:06


Dan W. wrote:

>>class X
>>{
>> smart_ptr<My_polymorhic_type> p_;
>>public:
>> int bar() const
>> {
>> return p_->this_is_also_a_const_function(); // compile time error
>>if
>>not
>> }
>>};

>That's neither a const, nor a non-const function of p_, you're calling;
>it's a function of what p points to. That a function is const means that it
>doesn't change the class state, i.e.: what _address_ the pointer points to.
>But the target at that address is _not_ part of the state of this class, so
>why should the constness of a member function of _this_ class have to bear
>responsibility for some class elsewhere, just because we have its pointer?

The problem in this case is that the function bar() is const, and thus so
must the this pointer to the class. I think this is what is causing the
problem in this example.

But, let me point out that this works to retain the const-ness of the
program: declaring bar() to be const is saying that you intend the function
to be a *read* method (as it is returning an int).

If you intend to violate this, you need to add a const_cast around the
pointer call, making it explicit that this is what you want to do, but then
why is bar() const?

Regards,
Reece

_________________________________________________________________
Send a funky MSN Messenger Christmas card http://www.msn.co.uk/christmascard


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk