Search code examples
c++memory-managementinitializationdata-members

Initializing Data Members with a Member Function


I have today learned the very useful new feature of C++ 11 which allows direct initialization of data members in the class declaration:

class file_name
{
    public:
    file_name(const char *input_file_name);
    ~file_name();

    private:
    char *file_name=nullptr;  //data_member is initialized to nullptr;
    char *Allocator(int buffer_size);  //code to dynamically allocate requested
                                       //size block of memory.
};

Is it possible to take this a step further with the new v11 rules and initialize a data member with the output of a member function:

class file_name
{
    public:
    file_name(const char *input_file_name);
    ~file_name();

    private:
    char *file_name=Allocator(MAX_PATH);  //data_member is initialized with a block of
                                          //dynamic memory of sufficient size to hold
                                          //and valid file name.;
    char *Allocator(int buffer_size);  //code to dynamically allocate requested
                                       //size block of memory.
};

Would this cause problems?


Solution

  • A non-static member function (usually) somehow depends on the state of the object it is called in. If this would not be the case, there would not really be a reason to make it a non-static member function. Now you want to call a function that depends on the state of your object before said object is completely constructed, i.e. its invariants the function might rely on are not necessarily established yet. So using such a function is potentially dangerous since e.g. the function might access uninitialized variables. Consider this example:

    class Fail {
        int a = fun() , b;
        int fun() {return b;}
    };
    

    Here a gets initialized before b, but with the (undefined) value of b. A static member function should be fine though.