Clarifying 'const' terminology
Bruno Medeiros
brunodomedeirosATgmail at SPAM.com
Sun Jul 9 02:28:37 PDT 2006
Derek Parnell wrote:
> 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
"However, in D they are one and the same thing - a class member must be
declared and defined at the same time."
Not entirely correct, remember d header files? What happens in D, is
that if there is a definition, then there must also be declaration
(they're the same actually). But there can be just a definition:
class Foo {
void func();
}
This means that in D, just as C++, there is no way for the compiler to
know in all cases whether the func changes or not the object instance.
Thus, it is necessary for the user to specify it.
--
Bruno Medeiros - CS/E student
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d-learn
mailing list