- status changed from new to accepted
The documentation says that you can use protected and private members in
contracts because "C++ provides programmers ways around access level
restrictions (e.g., friend and function pointers)". Next, we read that
"only public member functions shall check class invariants. Private and
protected member functions are allowed to brake class invariants because
private and protected member are part of the class implementation and not
of its specification".This 2nd statement is correct. The 1st statement means that in C++ you
can never prevent people from programming junk like this which will
break the public interface (the same can be done without static):
class x
{
public: static void pub ( void ) { std::cout << "pub" << std::endl; }
private: static void priv ( void ) { std::cout << "priv" << std::endl;
}
typedef void (*fptr) ( void );
public: static fptr bad ( void ) { return priv; }
};
int main ( void )
{
x::pub();
void (*priv) ( void ) = x::bad();
priv(); // calls a private function :(
return 0;
};
The call to priv via the function pointer is done outside the class
implementation but it won't check the invariants--but if you program
"bad" then you're on your own! That's all I wanted to say with the 1st
statement (which is actually an observation from The C++ Programming
Language, Stroustrup). I can clarify this in the docs.
I feel I have been misunderstood. Let me clarify. I understand how one can
overcame the member access restrictions in C++ with hacks. I do not think
you need to clarify it in the docs. The way I understand the docs is that
you use these hacks as rationale for allowing private and protected members
in contracts.
No. Private and protected members are allowed in contracts because
they can have pre and post even if they never check inv. Public
members are allowed in contract because they have pre, post, and also
check inv.
On a separate note, you cal always call a private or protected member
from a public scope using the access hacks. If you do so beware that
inv will not be checked (as they shouldn't because you are calling a
private or protected member) even if the call is made from a public
scope--you're on your own.
That's what I tried to say in the docs. I'll clarify the docs.
Log in to post a comment.