Logical const

Rainer Deyke rainerd at eldwood.com
Sun Nov 28 19:09:50 PST 2010


On 11/28/2010 17:29, bearophile wrote:
> Peter Alexander:
> 
>> If I give some const object to a function:
>> 
>> void render(const GameObject&);
>> 
>> GameObject obj; render(obj);
>> 
>> I can be sure that my object will come back unmodified.
> 
> render() is free to modify the objects contained inside GameObject,
> because that const isn't transitive.

This is simply not true.  Observe:

  class InnerObject {
  public:
    f();
  };

  class GameObject {
  public:
    void f() const {
      this->inner.f(); // Error: const object modified.
    }
  private:
    InnerObject inner;
  };

In C++, const is transitive for direct members.  It is only intransitive
for pointer/references, and even these can be made transitive through
the use of a transitive-const smart pointer class.


-- 
Rainer Deyke - rainerd at eldwood.com


More information about the Digitalmars-d mailing list