Reputation: 1749
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.
Upvotes: 0
Views: 539
Reputation: 41116
You can pass the size to the base class' constructor:
class base
{
base(size_):size(size_), p_array(new char[size_]) {}
}
Your derive class determines the size, though it needs to know it upon base construction:
class largebufferderived : public base
{
public:
largebufferderived() : base(77220) {}
}
Or you can initialize the buffer on demand (that's not always a good idea in multithreaded scenarions):
boost::shared_ptr<char> Buffer()
{
if (!p_Array)
p_array.reset(new unsigned char[size]);
}
Make p_Array private in the base class, so derived classes can access only through Buffer().
Alternatively, just add a "FinalConstruct" methood to call in the derived classes Constructors. Thi does not avoid calling it, but at least isolates WHAT needs to be done after all constructors were called.
btw. why shared_ptr, not shared_array?
Upvotes: 3
Reputation: 19800
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:
};
Upvotes: 4