C++/shared constant base class/derived class dilemma
My question is about how to do something that should be simple, but classes/inheritance doesn't seem to allow, at least in a forward manner.
Let's say our sample application needs to process (open, read, close) text files that represent different types of data for the application (Customer, Vendor, Invoice).
I would think of implementing a base class with the functions Open(), Read(), and Close(), and then have a derived class for each type of specialized files (Cust, Vend, Invoice).
I'd like to have a constant static string for the FileType, so each derived class could define their type:
the FileType class would define it as "CUST"
the FileType class would define it as "VEND"
the FileType class would define it as "INVC"
Defining this member in the base class will allow to have the Open(), and other text-file-specific functionality in the base class b/c all derived classes are text files. The FileType string will be part of the file path or filename, so only the base's Open() needs to concatenate it as needed.
There will be a member called ProcessData(), which will be implemented in each derived class for class-specific processing. The processing sequence of the whole process would be:
Open() // base class does this.
Read() // base class does this.
ProcessData() // derived classes implement this.
Close() // base class does this.
But if I declare this static constant string in the base class, I cannot have different values for the FileType in each one of the derived classes.
I want it to be static, so it's one for each derived class instance.
I want it to be constant, so it doesn't have to be initialized at runtime.
Would you please explain to me the solution for this dilemma?
In the past class, define a virtual function GetType which returns the file type (for efficiency, don't use strings "CUST", etc. but use an enum CUST, etc.). In each class, define GetType and return the enum value (the enum can be public in the base class). Only member functions can override base class functions, not static members. This is why you are unable to do what you want to with the static.