I have base class which is generic parser of some data, and I have multiple derived classes which provide specific access interface to data contained in parser. I can determine the type of derived class only after all data is parsed, since it depends on the hierarchy (there is the tree of base classes, which needs to be fully populated to determine derived class for each base).
What is the best way to create derived class from base class, avoiding unnecessary copying of the data? As of now, I'm creating derived using copy constructor of base (as below):
class Base
{
};
class Derived : public Base
{
Derived(const Base &base)
: Base(base)
{
}
};
, but this requires copying all the base data which is no necessary - I want base class to become derived without copying and deleting it if possible.
EDIT:
Base parser parses data file and stores data generically as map >, while derived classes provide specific access interface depending on hte actual data type stored. Derived classes may change and more can be added.
You've said that you must first parse all the data, and the question seems to suggest to me that you use Base
to do the parsing. (Note, subsequent OP edit has confirmed this to be the case.)
Then once the parsing is complete, you construct a Derived
from the Base
based on the data that was parsed. This suggests to me that Derived
is not just a parser, but some kind of container for the parsed data, as well as an actor on that parsed data. (Also confirmed.)
Having one class which both parses data and also contains parsed data and acts upon it is a violation of the Principle of Single Resposibility . Principles were meant to be broken, but I think that violating it in this case is causing you problems.
My suggestion is to break up your hierarchy.
std::map
. The workflow would be something like this:
shared_ptr
to the raw data container. You can provide the derived class with its own constructor, and parse only the data you need to determine it. Passing a pointer is a good idea aswell, because it doesn't involve memory allocation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.