Search code examples
c++classencapsulation

Is returning a class member a bad practice?


Given:

Class A
{
     private:
       double **CR;
     public:
       double **compute2D();
};

Suppose that I have a private 2D Array member:

double **CR;

And I have a member function:

Double ** Compute2D()

Function computer2D will return CR.

Is this a bad practice? Why? Should I use the getter and setter functions to return it?

And one more question: Am I using the garbage collector correctly?

A::~A()
{
    //Delete 2D array
    for(int i = 0; i < Rows; ++i)
    {
        delete [] CR[i];
    }

    delete [] CR;
}

Solution

  • Reterning a class method is perfectly fine if you want that class member to be readable outside the class, which is completely dependent upon what you're trying to accomplish. As for using a getter method, you already are; it is "good practice" to use such methods to create a more uniform, encapsulated setup for your class and therefore make it easier to edit the class later. Even if your function does other things (in this case, computes something in two dimensions), it's still a getter method.

    In this particular case, however, you're not returning a value; you're returning a double pointer to a value. This means that the user will be able to edit the data (which I'm guessing is an array) ouside the class, which is NOT a good thing. You should perform a deep copy of the data before returning it.

    As for using the garbage collector correctly: yes, you are. Although it's not called a garbage collector in C++, it's simply called freeing memory; a garbage collector is the name for a system that frees memory automatically.