C++ – How to delay the initialisation of a member in a C++ base class until the ctor of derived class is executed

c++

Here's the scenario:
I want define a base class that allocate some buffer once for all derived classes, while the size of the buffer varies among different derived classes. I could achieve it in this way:

class base
{
public:
     base():size(), p_array(0){}
private:
     size_t size;
     boost::shared_array<unsigned char> p_array;

};

in the derived class:

class derived
{
public:
     derived(size_t array_size):size(array_size)
     {
          p_array.reset(new unsigned char[size]);
     }    
};

However, in order to simplify the design of the derived class, I really want to put this line:

p_array.reset(new unsigned char[size]);

to somewhere in the base class, thus writing it only once. Is there any C++ design pattern could achive it?
Thanks.

Best Solution

sorry but why do you have 2 arrays (and 2 sizes)? Now if you create a derived class you have a 2 times a p_array. I think the compiler should give an error on this.

Don't you want this?

class base
{
public:
     base():size(), p_array(0){}
     base(size_t array_size):size(array_size)
     {
          p_array.reset(new unsigned char[size]);
     }
private:
     size_t size;
     boost::shared_ptr<unsigned char> p_array;

};

class derived
{
public:
     derived(size_t array_size):base(array_size)
     {
     }
private:
};