Search code examples
c++constructormemberdefault-constructor

Initialize members with deleted default constructor


In C++, if I want to have a member of a class that has no default constructor, I need to explicitly initialize it like this:

class a
{
   a(int)
   {
   }
};

class b
{
   a x;

   b() : x(3)
   {
   }
};

However, sometimes the initialization for, say, x, could not be so simple. It could either be a very very complicated formula or a whole, algorithmic function with fors and ifs that needs to be computed. I usually solve it like this:

class b
{
   a * x;
   b()
   {
      // Do some very complicated computations
      this->x = new a(result_of_complicated_computations);
   }
};

Which, however, forces me to delete the pointer at the moment of destruction, it slightly less performing and makes my code somehow untidy and ugly. I am really surprised that there is no way to compute parameters for constructors of members within the constructor of the class, without having to use this kind of tricks.

Are there more elegant solutions to this?


Solution

  • Use a helper function:

    class b
    {
        a x;
        b() : x(complicated_computation()) { }
    private:
        static int complicated_computation() {
            return result_of_complicated_computations;
        }
    };
    

    And the default-constructor isn't deleted, but undeclared.