Clarifying 'const' terminology

Derek Parnell derek at psych.ward
Sat Jul 8 16:20:59 PDT 2006


On Sun, 09 Jul 2006 06:05:11 +1000, Kirk McDonald  
<kirklin.mcdonald at gmail.com> wrote:



> There's another place you can put 'const' in C++:
>
> class A {
>      void bar(int i);
>      int foo() const;
> };
>
> This "const" ensures that the member function A::foo does not modify the  
> instance of A that you are calling it on. (If the function does do so,  
> it is a compile error.) This is an issue when you are dealing with const  
> instances of A:
>
> const A a;
>
> a.bar(12); // ERROR! a is const, A::bar is not
> a.foo();   // Okay
>
> I actually view this as necessary if we get a way to declare an instance  
> as immutable in D. (Honestly, I have few issues with C++ const, though  
> this "const-by-default for class instances" idea has merit, too.)

I can see why this would be a good thing in C++, because the declaration  
of A::foo() and the definition of A::foo() is not necessarily in the same  
source file or even written by the same person. This style of 'const' is a  
way to document a design decision in source code and thus have the  
compiler enforce the design.

However, in D they are one and the same thing - a class member must be  
declared and defined at the same time. So if the design decision is that  
A.foo() is not allowed to change any of the data members in an A object,  
there is no way to get the compiler to know about that design decision. So  
maybe it would be a useful debugging aid.

-- 
Derek Parnell
Melbourne, Australia



More information about the Digitalmars-d-learn mailing list