I'm writing two programs, let's say a calculator and a chess game. They share a lot of code (interface management, file opening/saving), and I'm trying to figure out the best practice to avoid repeating code.
My idea was to create a parent class, let's call it Generic_Program, which has all the common functions, and derive child classes.
The problem I run into is how I could call a derived class' function instead of the parent one. Conrete example with saving configuration and exiting:
class Generic_Program {
void SaveConfig() {
// Write general parameters to a file
}
void Exit() {
SaveConfig(); //First save configuration
// Configuration saved, do exit routines, like make window invisible, etc.
}
}
class Calculator : Generic_Program {
void SaveConfig() {
Generic_Program::SaveConfig(); //Write generic parameters
// Write calculator-specific data, like calculation results, etc.
}
}
class Chess : Generic_Program {
void SaveConfig() {
Generic_Program::SaveConfig(); //Write generic parameters
// Write chess-specific data, like player scores, etc.
}
}
Now, I'd like to be able to call Exit()
from both programs. The desired behaviour is that they both save their generic and specific data, then exit.
If I do it with the above code, it will call the parent class' SaveConfig() and thus will save only generic program data.
I could of course write specific Exit()
routines for child classes, but the point is to write shared code only once.
Is there a method to call SaveConfig()
of the children from the parent class? Or a best practice for avoiding repeated code in this case?