So here is what I know:
- It is wise not expose your ivars directly in your API; rather, use accessors
- A
const
pointer to a non-const
object simply means you can alter the object, but not redirect where the pointer points
Here is my situation:
I have a few related classes. I want to create a simple class that, via composition, combines these into one logical interface. Each of my enclosed classes already has a public and private distinction in its API so I do not mind exposing them directly to users of my parent class. This means that it would be overkill for me to write accessors for these ivars since the classes already manage what is public and what isn't. But, I don't want users to change the actual objects that are enclosed into this composed parent class.
So the only way I can think to do this is to use const
pointers to these objects, as such:
class Parent{
public:
EnclosedClass1*const ec1; //users can enjoy the public API of EnclosedClass
EnclosedClass2*const ec2;
void convenienceMethod(){
//performs inter-related functions on both ec1 and ec2
}
}
This way, there is no harm in letting someone directly interface with the API of ec1
and ec2
but, I want to make sure this is fairly foolproof in that at least that person cannot change the actual resource being manipulated, hence the const
pointers.
Does this make sense, is it a good use of const pointers?
Alternately, I could make them private
entirely, forget the pointers (this class manages these objects anyway), and just do the extra work to write accessors for the public functions contained in these objects. But that just seems overkill, right?