Search code examples
c++initializationconstantsinitializer-list

constant member in class


I have this class:

class model
{
private:
    link_list list;
    float parameter_B1;
    float parameter_B0;
public:
    model();
    float getparameter_B1() const;
    float getparameter_B0() const;
    float predict();
    void info();
};

In which float parameter_B1 and float parameter_B0 are constant , but in order to initialize them , I have to enter constructor body and read a file and using that file's data to find value of these two attributes, but once I set them ,they won't change again.(so I guess they are count as constant)

like this:

model::model()
{
    char filename[300];
    cout << "enter file name(path\\filname.txt):" << endl;
    cin >> filename;
    FILE* fp;
    fp = fopen(filename, "r+");
    float x, y;
    if (fp == NULL)
    {
        cout << "Unable to open the file!" << endl;
        exit(EXIT_FAILURE);
    }
    else
    {
        while (!feof(fp))
        {
            if (fscanf(fp, "%f\t%f", &x, &y) == 2)
            {
                Pair p(x, y);
                list.insertNewNode(p);
            }
        }
    }
    Pair _average = list.average();
    parameter_B1 = list.parameters1(_average);
    parameter_B0 = list.parameters2(_average, parameter_B1);
}

but if I change my class to:

class model
{
private:
    link_list list;
    const float parameter_B1;
    const float parameter_B0;
public:
    model();
    const float getparameter_B1() const;
    const float getparameter_B0() const;
    float predict();
    void info();
};

I will receive these error "model::model()" provides no initialize for:

1. const member "model::parameter_B1"

2. const member "model::parameter_B0"

, but as you can see I can't use initializer list.

what should I do? is not declaring constant variable my only solution?


Solution

  • with delegating constructor, you might do

    std::tuple<link_list, float, float> read_model_file()
    {
        char filename[300];
        cout << "enter file name(path\\filname.txt):" << endl;
        cin >> filename;
        // ...
        Pair _average = list.average();
        parameter_B1 = list.parameters1(_average);
        parameter_B0 = list.parameters2(_average, parameter_B1);
        return {std::move(list), parameter_B0, parameter_B1};
    }
    
    class model
    {
    private:
        link_list list;
        const float parameter_B0;
        const float parameter_B1;
    public:
        model() : model(read_model_file()) {}
        model(std::tuple<link_list, float, float> t) :
            list(std::get<0>(std::move(t))),
            parameter_B0(std::get<1>(std::move(t))),
            parameter_B1(std::get<2>(std::move(t)))
        {}
        // ...
    };