2
I wonder if in c++ you can increment an existing class by inserting new methods, without touching the class source code directly.
For example, if the class below is part of an external library that should not be changed, containing 2 methods:
class original
{
public:
void metodo1() {
std::cout << "método 1" << endl;
}
void metodo2() {
std::cout << "método 2" << endl;
}
};
So within my code, I would like to increment this class inserted a third method:
void metodo3() {
std::cout << "método 3" << endl;
}
How would that be possible?
You can’t extend the class without modifying the class itself. However, there are a number of strategies and best practices that can and should be used in such cases as this, such as the Open/Close principle. A popular strategy is to use functions that accept the class as a parameter (see Factory, Strategy, or Command-type software design standards) or to design the class with its extension in mind (Visitor-type software design standard).
– RAM