I have a class which stores a pointer to a data chunk and the size of the data. It implements operations like 'head', 'tail',... but it is irrelevant from the question's point of view. I use this instead of std::vector where I do not want deep copying. However I need to copy the data sometimes, so I have a member function 'duplicate' to do it.
struct ByteArray {
char* data;
int size;
ByteArray(char* data, int size) : data(data), size(size) {}
ByteArray duplicate() const {
char *duplicatedData = new char[size];
memcpy(duplicatedData, data, size);
return ByteArray(duplicatedData, size);
}
};
Now I have a derived class - extending the previous class, where I need a duplicate method too, which calls the base class' duplicate. I have managed to solve it by casting both objects to the base class, but I suspect that this is not the best solution. Am I missing a more obvious solution? Also is this class the right solution to the original problem (not having deep copy) or there is standard solution what I'm not aware of?
struct Foo : ByteArray
{
int bar;
... // more members
Foo(ByteArray &bytes, int bar) : ByteArray(bytes), bar(bar) {}
Foo duplicate() const {
Foo dup = *this;
static_cast<ByteArray&>(dup) = ByteArray::duplicate();
return dup;
}
};