Let's Complain the Irresponsible keyword 'const' in C++



as we were told, the 'const' methods of a C++ class will protect its members from being changed . it makes me so confident that 'const' methods are absolutely safe until someday i found a case which may be very often to occur but likely to be overlooked . by instinct i thought if C++ engaged that members are not to be changed, all the data will keep unchanged . also by instinct i give the same treat to the indirect data, say data involved by a pointer member. 

but C++ itself doesn't think so ! it only protect the member pointer, but exclude the data pointed by the pointer . 

similar rules to the methods of members . for direct members, their non-const methods are forbid to call, but no limitation if call by a pointer . 


for example :


class A
{
public:
    void set() {}
    void get() const {}
    int d;
};
class B
{
public:
    void func() const;
    A  a;
    A* p;
}
void B::func() const
{
    a.d = 0 ;   // not allowed
    a.set() ;   // not allowed
    a.get() ;   // allowed
    p = &a ;    // not allowed
    p->d = 0 ;  // allowed
    p->set() ;  // allowed
    p->get() ;  // allowed
}


你可能感兴趣的:(VC,JAVA,QT)