Home > Back-end >  Is it possible to convert virtual non-static to static method without doing major refactoring?
Is it possible to convert virtual non-static to static method without doing major refactoring?

Time:01-05

Consider the following:

class RecordCommon {
public:
   virtual const char* GetShortName(void) const = 0;
   ...
   virtual void DoSomeWork(void);
};

class RecordCLDT : public RecordCommon {
   virtual const char* GetShortName(void) const { return "CLDT"; }
};

void RecordCommon::DoSomeWork(void) {
   ...
   log(GetShortName());
   ...
}

What I want to have is static method like RecordCLDT::GetShortName(void) that would return"CLDT" without doing major refactoring of the project. Maybe this could be done by some macro or smart template technique?

I need to have RecordCommon::DoSomeWork(void) calling the correct GetShortName() function which it wouldn't if I just replace virtual GetShortName() with static one.

Re-writing every single child class of RecordCommon would be very time-consuming especially since virtual GetShortName() is used in the code.

CodePudding user response:

No, and you shouldn't want to. Anything you would do yourself would end up behaving like virtual anyway.

Just because you aren't accessing any of the data members of RecordCLDT, it doesn't mean you can make it static, you still need it to be an override of the base class member to call the right thing.

CodePudding user response:

virtual functions work because there is information hidden in the object that tells the system what object the pointer/reference really points to. This is what allows the correct function to be called for a given object.

If you want to remove virtual functions, you must replace this functionality. That is, instead of having hidden data in the object that says which kind of object it is, you must have explicit data in the object, which different functions will look at to tell which type it really is and therefore how to behave.

This is not a trivial thing to do, and how best to do it depends on a variety of factors. You can't just make a static member, rip out some virtuals, and expect everything to still work. The data that says what type the object is still has to be there and must be accessible from the base class. If you remove the implicit data, you must add explicit data.

  • Related