Re: Static virtual functions?
gw7rib@aol.com wrote:
I appear to need a static virtual member function, which it seems I
can't have. I'm trying to do something like the following:
class Base {
virtual void writetofile() = 0;
virtual void readfromfile() = 0;
(something here) char *name(); };
class Deriv1 : public Base {
virtual void writetofile();
virtual void readfromfile();
(ditto) char *name() { return "Deriv1"; } };
class Deriv2 : public Base {
virtual void writetofile();
virtual void readfromfile();
(ditto) char *name() { return "Deriv2"; } };
Now I want to write them to a file doing something like:
write (x -> name); x -> writetofile();
which requires name to be a virtual function. But I also want to do:
read(type);
if (strcmp(type, Deriv1::name) == 0) { x = new Deriv1; x ->
readfromfile(); }
if (strcmp(type, Deriv2::name) == 0) { x = new Deriv2; x ->
readfromfile(); }
which requires name to be a static member function.
Any suggestions? I want to avoid having to duplicate the names in
different places.
class Deriv1 : public Base {
public:
static const char* const name;
virtual const char *get_name() { return name; } };
const char* const Deriv1::name = "Deriv1";
Now you can get the name as constant from the class type as well as from
a class instance.
However, it seems that you want to implement your own (de)serialization.
There are solutions for this job around. You might want to give them a look.
First of all somewhere you should have an object type repository to
dispatch the deserialization. Virtual functions won't help you since you
do not have a typed object at this time. This is the job you did quite
ineffectively by the strcmp(type, Deriv1::name cascade. There are
significantly more sophisticated and faster solutions for this purpose.
Have a look at http://www.boost.org/libs/serialization/doc/tutorial.html
Furthermore, C++ programs should not contain char* objects. They are
nearly always risky. You should avoid char* wherever possible and use
std::string or const char* instead.
Marcel