Hello,
I am quite new to C++, would someone explain / provide link about class wrappers: what are they, when are they used, when not?
Thank you.
Cristian
Hello,
I am quite new to C++, would someone explain / provide link about class wrappers: what are they, when are they used, when not?
Thank you.
Cristian
A wrapper class extends the functionality of another class, or provides an interface that is easier to use. A good example is if you have a class that prints text. It takes strings as input and writes them to a chosen output:
Now say we want to translate the text to german and then print it. We could add the functionality to the PrintText class, but a more elegant solution would be to wrap a translation class around it:Code:class PrintText { public: void print ( string text, fstream file ) { // Print text to file } };
That's the basic idea.Code:class PrintText { public: void print ( string text, fstream file ) { // Print text to file } }; class GermanPrintText { PrintText pt; string trans_buffer; public: GermanPrintText ( string text ) { trans_buffer = text; } void translate( fstream file ) { // Translate text pt.print ( trans_buffer, file ); } };
-Prelude
My best code is written with the delete key.
Why use a wrapper as opposed to a derived class?
class GermanPrintText : public PrintText
fletch
"Logic is the art of going wrong with confidence."
Morris Kline
>Why use a wrapper as opposed to a derived class?
Style and elegance. I personally would rather write a wrapper than extend the inheritance tree. In C++ I can't think of any reason to use one over the other, so it's a question of personal preference.
-Prelude
My best code is written with the delete key.
What if the original class didn't have virtual methods (including a virtual destructor)? Then inheritance is a nono, derived classes can't be destroyed safely with a pointer to a base class.
What if you want to change a classes interface, say, implement a stack with a vector? Inheritance preserves the old interface, but random access doesn't make sense with a stack.