There is no general method in C++ to protect yourself from illegal pointer accesses, but there are idioms you can use to help protect yourself.
Keep your classes as representing concepts/objects and don't expose direct access to any pointers they might contain. Prefer for example descriptive methods, or for container-like classes begin
/end
style methods.
When managing pointers, prefer first to use a standard container such as vector
. They're highly tuned and debugged and will prevent many problems since they already have all the right constructors, assignment, destructor, etc.
If a standard container isn't possible prefer a smart pointer such as unique_ptr
, scoped_ptr
, shared_ptr
or weak_ptr
depending on your pointer needs. By using an appropriate smart pointer, again you make it almost impossible to unintentionally make coding mistakes.
Even using all these guidelines you can always bypass any protection you've attempted to implement. If you find yourself using a lot of casts you should step back and re-examine your design.
In your case not only would I make pA
not be accessible via accessor, I wouldn't make it a raw pointer either.