I was surprised to find this “hole” in “const”ness:
#include <stdio.h>
class A
{
int r ;
public:
A():r(0){}
void nonconst()
{
puts( "I am in ur nonconst method" ) ;
r++;
}
} ;
class B
{
A a ;
A* aPtr ;
public:
B(){ aPtr = new A() ; }
void go() const
{
//a.nonconst() ; // illegal
aPtr->nonconst() ; //legal
}
} ;
int main()
{
B b ;
b.go() ;
}
So basically from const method B::go(), you can invoke the non-const member function (aptly named nonconst()) if object of type A is referenced by a pointer.
Why is that? Seems like a problem (it kind of was in my code, where I found it.)
When and object of type
Bis const, then all of its members are const, which means its two members are, for the duration ofB::go(), effectivelyThe first is a constant object of type
A, on which you can only call const member functions. The second, however, is a constant pointer to a non-constantA. You could not legally sayaPtr = <anything>from within the functionB::go(), since that would modifyaPtr, which is constant.A pointer to a constant
Awould be declared asA const* aPtrorconst A* aPtr, which would then make calling the non-constantA::nonconst()illegal.