If you return a pointer or non-const reference to your private data member via a public method, it is pointless to make it private. You could make the property public as well.
This basically means you allow to manipulate the member outside of the class. IMO this is considered a bad practice, or even an anti-pattern because the class cannot depend on its own state. This is very important.
E.g: imagine you have a pointer, and somebody sets it to null
. Even the private methods would need to check for it, even if internally such state is impossible to reach.
Returning normal members, such as classes is considered a bad practice because it involves copying of whole objects. Usually it is better to return a reference or probably preferably const reference.
The getters in turn would allow you to put const
constraints. In both cases, pointers and references.
Also please note, that in such cases usually, one provides two methods. compute
and get
. Currently you can access your member only by computing it!
I won't go so far to suggest you to switch to std::vector
as I do not know what you need, and vectors are not good for everything. So sticking with pointers, this is the safe way to go:
class A
{
private:
double **CR;
public:
double const * const * compute2D();
double const * const * getCR();
};
double const * const * A::compute2D(){
return CR;
}
double const * const * A::compute2D(){
/*Heave CPU stuff*/
return CR;
}
int main(){
A a;
double const* const* tmp = a.compute2D();
tmp[1][2] = 0; //this will fail to compile
tmp[1] = 0; //this will fail too
double get_test = tmp[1][2]; // this passes!
}
Notice double const
qualifiers. It is important to protect each level of pointer references.