Thread: Wrapper classes

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    43

    Wrapper classes

    Hi all

    Real quick question this one... can someone please explain to me what a wrapper class is and what it is useful for? My tutorial book isn't very clear and for some reason I can't find a tutorial that will explain to me what one is!

    This is in terms of "a wrapper to a container". My book seems to imply that it will help to manipulate a container such as vector or list, using data structures such as stack and queue. However I'm confused by this somewhat vague explanation - does this mean that the elements of the container are taken / used by the wrapper class in a queue / stack / (whatever) system?

    If someone could show me some example code of a wrapper being implemented I get the feeling the visual aid would also be helpful - this is somat my book is also lacking. :-P

    Thanks a lot :-)

  2. #2
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    There may be a more precise definition, but I just think of a wrapper class as being a class which provides a simpler or easier to use interface to existing code.

    For example, you could print coloured text to the screen by manipulating bytes in video memory (assuming you were using an old compiler and didn't care about portability). But this is a pain, so people created ANSI escape sequences to make writing coloured text easier. (I know this isn't an actual class, but it's the same idea.)

    There are other reasons to use wrapper classes; portability, for example. If you were writing a GUI program, you might have a Windows implementation and a Linux implementation. To allow the majority of the code to interact with the GUI without using Windows or Linux-specific code, you could wrap the GUI code in a wrapper class.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    In the case of std::stack and std:queue these are container adaptors that provide an interface to a template parametrized container that enable stack and queue operations. The methods (member functions) of the stack and queue classes server as aliases to the underling container's methods.

    So they are wrapper classes in the sense that the methods don't do much more than call methods of the underling container. (They also independently keep track of the size, but that is a minor thing.)

    The purpose of stack and queue is to provide a generic interface to a simple and common set of tasks who's implementation can easily be decided independently: it is very easy to change the underlying container as long as it has a specific set of functions implemented.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    43
    OK. First thing to bear in mind is I am a noob lol, so I'm struggling to keep up with what you're both saying.

    So the wrapper class literally "wraps" the code - would the Christmas present wrapper analogy work?!! (told you I'm a noob). If so how does it hold the code - using containment? Could someone please write out a basic example of a wrapper class so I can see what's going on.

    DWKs - the printer example means nothing to me I'm afraid! I could stab a guess at what you're saying about GUI program - are you saying the methods in your wrapper class would then make the GUI acceptable to either Windows or Linux??

    lol sorry - I've not been learning very long and have to squeeze it in around job, wife etc!!

  5. #5
    Registered User
    Join Date
    Mar 2009
    Posts
    43
    DWKs - if you'd be willing, if you could show me how a wrapper class would be used in order to ensure portability to different platforms I'd really appreciate it. Like I say, I think visual aid will be the answer here!

    Thanks :-)

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The wrapper just provides a layer between you and whatever it is that you're doing. In the GUI example, there would be completely different code for a Win GUI and a linux (whichever flavor) GUI. The wrapper class would give you one set of functions to use no matter what. The class would then call who-knows-what, based on what underlying library you're building on. And more to the point, not only do you not know what's being called, you don't need to (or want to) know -- that's the job of the wrapper, to be between you and the library.

  7. #7
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    tabstop is really talking about the facade design pattern, which is closely related, but I would make a distinction.

    A wrapper is just a object with methods or set of functions that just call another set of functions in their place. So it might look something like this:
    Code:
    class Wrapper
    {
      Internal obj;
      public:
      int func1(int param){
        return obj.objfunc1(param);
      }
      void func2(int param){
        obj.objfunc2(param, "constant value user does not need to know about", NULL);
      }
    }
    The key feature again is that the wrapper functions do not do much besides call the underlying object.

    So it can be used as a facade of a complex system. Wrappers are also used to collect statistical information about the underlying functions, like how many times a function is called, or how long it takes.
    Last edited by King Mir; 06-08-2009 at 03:02 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    [edit] I'm not really talking about a wrapper class here either (see below), but hopefully it's close enough . . . . [/edit]

    Well -- okay. It will have to be a contrived example I'm afraid.

    Let's say I have a program which can output to the command line with cout, or to a console using ncurses (I'll explain what that is in a minute). I might then have the class Screen as my wrapper class.
    Code:
    class Screen {
    public:
        virtual void display_message(std::string text);
    };
    So for the cout implementation, this is really easy.
    Code:
    class ScreenCout : public Screen {
    public:
        virtual void display_message(std::string text) {
            std::cout << text << std::endl;
        }
    };
    But with the ncurses implementation, suppose I also add the capability to scroll back to see the history of what has already been displayed. I'll have to store each line of text as it is printed so that it can be re-displayed as necessary. A sketch of the class might look like this.
    Code:
    #include <vector>
    
    class ScreenNCurses : public Screen {
    private:
        int current_top;
        std::vector<std::string> displayed;
        bool at_bottom;
    public:
        virtual void display_message(std::string text) {
            displayed.pish_back(text);
            if(at_bottom) scroll(1);
        }
    protected:
        virtual void scroll(int lines) {
            current_top += lines;
            // repaint lines starting at current_top from displayed[]
        }
    };
    You see how completely different the implementation is? They both do the same thing, but the ncurses version has to remember everything that was printed to provide history.

    That actually isn't a very good example. It's a good example of an interface with differing implementations, but a wrapper class typically provides more or less the same functionality using e.g. different libraries. But I didn't want to have to make up too many different libraries so I guess I'll let it be.
    Last edited by dwks; 06-08-2009 at 03:04 PM.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Registered User
    Join Date
    May 2009
    Posts
    37
    Quote Originally Posted by Know_Your_Role View Post
    OK. First thing to bear in mind is I am a noob lol, so I'm struggling to keep up with what you're both saying.

    So the wrapper class literally "wraps" the code - would the Christmas present wrapper analogy work?!! (told you I'm a noob). If so how does it hold the code - using containment? Could someone please write out a basic example of a wrapper class so I can see what's going on.

    DWKs - the printer example means nothing to me I'm afraid! I could stab a guess at what you're saying about GUI program - are you saying the methods in your wrapper class would then make the GUI acceptable to either Windows or Linux??

    lol sorry - I've not been learning very long and have to squeeze it in around job, wife etc!!
    When someone first told me the term wrapper class I thought they meant rapper class as it talks to another class. Actually the definition more or less works that way too. LOL

    In any case, I generally use them to make things portable as dwks was talking about. For instance I have (w)rapper classes that talk to DirectX and OpenGL. That way I can program using my own classes and later run my program with either graphics library.

  10. #10
    Registered User
    Join Date
    Mar 2009
    Posts
    43
    OK lets see if I'm getting the idea (and there's a good chance I'm not!!). I could have two separate classes that inherit from the wrapper class (say one is Windows code and the other Linux). They both do the same thing but in different ways but I want my program (say a GUI) to work with both. Therefore I'll ensure my wrapper class can speak to both and pass on the data to be used with my program correctly.

    I'd see it as being something like this:

    Code:
    class Wrapper
    {
    public: 
    virtual void Display_text () {Text();} // Text() might be in my program being wrapped
    }
    
    class Windows : public Wrapper
    {
    public:
    virtual void Verson_1 () {Display_text();}
    }
    
    class Linux : public Wrapper
    {
    public:
    virtual void Version_2 () {Display_text();}
    }
    This way although Windows and Linux are using different functions, they're going to eventually do the same thing as they're going to end up calling functions in the wrapper class - the wrapper class is essentially negotiating between windows / linux and the GUI program.

    Argh man sorry I get the feeling this isn't right but I'm really struggling to get my head round this one!!

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Often, it's the other way around.
    You have a common interface--class--that works on any operating system.
    This class derives from another class, and that class is OS-defined, meaning that its implementation--how it works--is different depending on what OS you use.

    You actually mentioned a good analogy yourself: Christmas present wrapper analogy.
    The present is what you are wrapping and the the present paper is the wrapper itself.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Mar 2009
    Posts
    43
    But what you're saying doesn't make logical sense to me. You're saying that the wrapper class will derive from the OS-defined class - so surely what is in the wrapper class will be restricted to how that specific OS works, unless you're using multiple inheritence? The wrapper must be the "middle man" - so the only way I can see it working is if the wrapper is derived from two different OS's using multiple inheritence then the GUI deriving from the wrapper?

    I really thought would take a two-sentence answer from one person lol :-S I know I've asked a lot already here but if someone could show code of how the windows / linux - GUI example mentioned above would work that might make things more clear.
    Last edited by Know_Your_Role; 06-09-2009 at 12:23 PM.

  13. #13
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by Know_Your_Role
    You're saying that the wrapper class will derive from the OS-defined class - so surely what is in the wrapper class will be restricted to how that specific OS works?
    In the scenario that Elysia gave, inheritance is probably not appropriate, except maybe for private inheritance. More likely you would use composition, providing an interface that "wraps" the OS specific class. The member functions of this new class would then use the interface of the OS specific class.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Know_Your_Role View Post
    But what you're saying doesn't make logical sense to me. You're saying that the wrapper class will derive from the OS-defined class - so surely what is in the wrapper class will be restricted to how that specific OS works, unless you're using multiple inheritence? The wrapper must be the "middle man" - so the only way I can see it working is if the wrapper is derived from two different OS's using multiple inheritence then the GUI deriving from the wrapper?

    I really thought would take a two-sentence answer from one person lol :-S I know I've asked a lot already here but if someone could show code of how the windows / linux - GUI example mentioned above would work that might make things more clear.
    I merely twisted your example around.
    Alright, how about this scenario:
    Code:
    class Wrapper
    {
    public:
        void PrintText(const std::string& Text);
    }
    
    void Wrapper::PrintText(const std::string& Text)
    {
    #ifdef WINDOWS
        // Windows specific code to print text here
    #endif
    #ifdef LINUX
        // Linux specific code to print text here
    #endif
    //etc
    }
    The wrapper would call OS-specific APIs depending on what OS it is compiled on.
    Hence it "wraps" the OS API calls.
    The class itself is a wrapper.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    Registered User
    Join Date
    May 2009
    Posts
    37
    Wrapper is kind of a generic term. There is not standard way of wrapping something. For instance you could write two classes with the same name that support the same functions for different operating systems and just include the one you want at compile time.

    However if you wanted to be able to swap things out at run time you could use the virtuals. Allow me to modify your code a bit

    Code:
    class IOWrapper
    {
    public: 
    virtual void Display_text () = 0;
    }
    
    class IOLibraryXWrapper: public IOWrapper
    {
    public:
    virtual void Display_text(char *str) {SomeWindowsOSDisplayTextFunction(str);}
    }
    
    class IOLibraryYWrapper: public IOWrapper
    {
    public:
    virtual void Display_text(char *str) {SomeLinuxOSDisplayTextFunction(str);}
    }
    Now at the beginning of your program you create either an object of IOLibraryXWrapper or IOLibraryYWrapper depending on whether you want to run with IOLibraryX or IOLibraryY. However when you use it you simply pass around (or make it a global, singleton or whatever) a pointer to IOWrapper. So the rest of your code doesn't need to know what IO library you are using. Now if someone comes out with IOLibraryZ you can make a wrapper for that too and your program will still work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 10:47 AM
  3. WinAPI wrapper classes
    By Hunter2 in forum Windows Programming
    Replies: 8
    Last Post: 12-14-2004, 05:22 PM
  4. Exporting VC++ classes for use with VB
    By Helix in forum Windows Programming
    Replies: 2
    Last Post: 12-29-2003, 05:38 PM
  5. wrapper classes?
    By curlious in forum C++ Programming
    Replies: 6
    Last Post: 08-27-2003, 09:26 PM