static members and encapsulation in c++

885 views Asked by At

Let us assume the following class:

class FileManipulator
{
    static InputTypeOne * const fileone;
    InputTypeTwo *filetwo;

    public:
    FileManipulator( InputTypeTwo *filetwo )
    {
        this->filetwo = filetwo;
    }
    int getResult();
};

FileManipulator uses data from both files to obtain output from getResult(). This means multiple iterations over filetwo and multiple constructions of FileManipulators via iterations for different InputTypeTwo objects. Inputs are, let us say, some .csv databases. InputTypeOne remains the same for the whole task.

The program itself is multi-modular and the operation above is only its small unit.

My question is how can I handle that static field in accordance with the object-oriented paradigm and encapsulation. The field must be initialized somehow since it is not a fixed value over different program executions. As far as I understand C++ rules I cannot create a method for setting the field, but making it public and initializing it outside of any class (FileManipulator or a befriended class) seems to me at odds with the encapsulation.

What can I do then? The only thing that comes to my mind is to do it in a C manner, namely initialize it in an isolated enough compilation unit. Is it really all I can do? How would that be solved in a professional manner?

edit

I corrected pointer to constant to constant pointer, which was my initial intention.

2

There are 2 answers

10
pvgoran On

You can write a public static method of FileManipulator that would initialize the field for you:

static void init()
{
  fileone = something();
}

And then call it from main() or some place where your program is being initialized.

2
Max Shifrin On

One way of doing this which comes to mind is:

In the .cpp file

FileManipulator::fileone = NULL;

Then modify constructor to do the following:

FileManipulator( InputTypeTwo *filetwo,  InputTypeOne  *initValue = NULL)
{
    if(fileone == NULL)
    {
        fileone = initValue;
    }
    this->filetwo = filetwo;
 }

Or you could also define an init function and make sure to call it before using the class and after the CTOR. the init function will include the logic of how to init fileone.