What is the meaning of a C++ Wrapper Class? - c++

I have a little trouble in understanding a wrapper class. It would be great if some one could help providing apt examples.
What is a C++ Wrapper Class and what are the circumstances of writing it ?
What is it's use any way ?
Thanks.

A "wrapper class" is a de facto term meaning a class that "wraps around" a resource; i.e, that manages the resource. When people write a wrapper, then, they are doing something like this:
class int_ptr_wrapper
{
public:
int_ptr_wrapper(int value = 0) :
mInt(new int(value))
{}
// note! needs copy-constructor and copy-assignment operator!
~int_ptr_wrapper()
{
delete mInt;
}
private:
int* mInt;
};
This class manages ("wraps") a pointer to an int. All resources should be wrapped in some fashion, for cleanliness (no explicit clean up code or noise) and correctness (destructor is guaranteed to run; cannot forget to clean up, and safe with exceptions).
This pattern is called Scoped-bound Resource Management (SBRM), though a far more common (but most esoteric) name is Resource-Acquisition is Initialization (RAII). The idea is to bind a resource's clean-up to a destructor, for the reasons given above: the scope handles the rest.
Note that I said it was missing a copy-constructor and copy-assignment operator. This is due to the Rule of Three. (See linked question for detailed explanation.) The simplest way to correctly implement this rule is with the copy-and-swap idiom, explained here.
Sometimes, it's not pragmatic to write wrapper class for resource clean-up, usually when the resource is unique or used once. (Or with transactional programming.) The solution to this is called scope guard, a way of writing clean-up code inside the function that needs it.
You may find more information by searching for it in your favorite search provider (that is, Google), or going to the "primary" document here. Note that Boost provides a utility for this, as it usually does for good idioms.

A wrapper is just some smallish class whose purpose is to provide a different interface than the thing it wraps. For example, it is common to take a C API and write one or more classes that "wrap" it to provide an object-oriented interface rather than a procedural one.

You asked for circumstances of writing wrapper classes.For example, if you are in a company that makes use of different types of cameras, let us say USB, firewire etc. Each of the manufacturers will provide a different set of functions through an API to start the camera, set the parameters and read the image stream from it.
Now the programmer who builds the applications in your company need to be insulated from all the specific details in the various APIs. Now, what you can do is write a wrapper class around the APIs for each of the cameras or smarter, just one class with simple functions, wrapping around the existing code provided by the API.
For instance, we can design classes
MyUSBCameraWrapperClass,
MyFirewireCameraWrapperClass
with some member functions like
setFrameRate(int fps),
getImgFrame(*framebuffer), etc.
The programmers in your company can then use MyUSBCameraWrapperClass usbcam; usbcam.setFrameRate(30), etc. You get the point??

A wrapper class is a class that wraps a functionality with another interface.
Suppose you have the function f():
void f() { std::cout << "hello\n"; }
A simple wrapper class might be
class C {
f() { std::cout << "hello\n"; }
};
You might write a wrapper when your existing codebase expects a particular interface. This is the essence of the adapter design pattern. Or you might wrap a function in a class if you wish to maintain state for that function. Or you might wrap a function in a class' constructor or destructor if you want it to conveniently and automatically be called for you in a correct and deterministic manner. And the list goes on.

I use two kinds:
resource wrappers for function pairs provided by the OS like
UNIXs: open/close, mmap/munmap, dlopen/dlclose
Windows: CreateFile/DestroyHandle, CreateFileMapping/CloseHandle, LoadLibrary/FreeLibrary
functional wrappers for functions provided by the OS like
UNIXs: write, read, dlsym
Windows: ReadFile, WriteFile, GetProcAddress
The resource wrapper makes certain, that compiler generated code worries about the destruction of the resource created by the constructor via what is today called RAII. It is easy to combine such classes via base/member class relationships into complex classes.
In case of the creation function fails, a system error exception is thrown, providing rich error information about the error.
The functional wrapper is used instead of the plain OS function. Also in case of failure a system exception is being thrown.
This way somebody using my code doesn't need a debugger and debug code to find out what is failing in a complex environment with many libraries and processes and remote machines.
Also these wrappers provide some OS abstraction -- the code using them does not have to worry about OS differences.

Related

C++ Class References

Coming from Delphi, I'm used to using class references (metaclasses) like this:
type
TClass = class of TForm;
var
x: TClass;
f: TForm;
begin
x := TForm;
f := x.Create();
f.ShowModal();
f.Free;
end;
Actually, every class X derived from TObject have a method called ClassType that returns a TClass that can be used to create instances of X.
Is there anything like that in C++?
Metaclasses do not exist in C++. Part of why is because metaclasses require virtual constructors and most-derived-to-base creation order, which are two things C++ does not have, but Delphi does.
However, in C++Builder specifically, there is limited support for Delphi metaclasses. The C++ compiler has a __classid() and __typeinfo() extension for retrieving a Delphi-compatible TMetaClass* pointer for any class derived from TObject. That pointer can be passed as-is to Delphi code (you can use Delphi .pas files in a C++Builder project).
The TApplication::CreateForm() method is implemented in Delphi and has a TMetaClass* parameter in C++ (despite its name, it can actually instantiate any class that derives from TComponent, if you do not mind the TApplication object being assigned as the Owner), for example:
TForm *f;
Application->CreateForm(__classid(TForm), &f);
f->ShowModal();
delete f;
Or you can write your own custom Delphi code if you need more control over the constructor call:
unit CreateAFormUnit;
interface
uses
Classes, Forms;
function CreateAForm(AClass: TFormClass; AOwner: TComponent): TForm;
implementation
function CreateAForm(AClass: TFormClass; AOwner: TComponent): TForm;
begin
Result := AClass.Create(AOwner);
end;
end.
#include "CreateAFormUnit.hpp"
TForm *f = CreateAForm(__classid(TForm), SomeOwner);
f->ShowModal();
delete f;
Apparently modern Delphi supports metaclasses in much the same way as original Smalltalk.
There is nothing like that in C++.
One main problem with emulating that feature in C++, having run-time dynamic assignment of values that represent type, and being able to create instances from such values, is that in C++ it's necessary to statically know the constructors of a type in order to instantiate.
Probably you can achieve much of the same high-level goal by using C++ static polymorphism, which includes function overloading and the template mechanism, instead of extreme runtime polymorphism with metaclasses.
However, one way to emulate the effect with C++, is to use cloneable exemplar-objects, and/or almost the same idea, polymorphic object factory objects. The former is quite unusual, the latter can be encountered now and then (mostly the difference is where the parameterization occurs: with the examplar-object it's that object's state, while with the object factory it's arguments to the creation function). Personally I would stay away from that, because C++ is designed for static typing, and this idea is about cajoling C++ into emulating a language with very different characteristics and programming style etc.
Type information does not exist at runtime with C++. (Except when enabling RTTI but it is still different than what you need)
A common idiom is to create a virtual clone() method that obviously clones the object which is usually in some prototypical state. It is similar to a constructor, but the concrete type is resolved at runtime.
class Object
{
public:
virtual Object* clone() const = 0;
};
If you don't mind spending some time examining foreign sources, you can take a look at how a project does it: https://github.com/rheit/zdoom/blob/master/src/dobjtype.h (note: this is a quite big and evolving source port of Doom, so be advised even just reading will take quite some time). Look at PClass and related types. I don't know what is done here exactly, but from my limited knowledge they construct a structure with necessary metatable for each class and use some preprocessor magic in form of defines for readability (or something else). Their approach allows seamlessly create usual C++ classes, but adds support for PClass::FindClass("SomeClass") to get the class reference and use that as needed, for example to create an instance of the class. It also can check inheritance, create new classes on the fly and replace classes by others, i. e. you can replace CDoesntWorksUnderWinXP by CWorksEverywhere (as an example, they use it differently of course). I had a quick research back then, their approach isn't exceptional, it was explained on some sites but since I had only so much interest I don't remember details.

Is it better to take object argument or use member object?

I have a class which I can write like this:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader&) = 0;
virtual ~FileNameLoader(){}
};
Or this:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader&, Logger&) = 0;
virtual ~FileNameLoader(){}
};
The first one assumes that there is a member Logger& in the implementation of FileNameLoader. The second one does not. However, I have some classes which have a lot of methods which internally use Logger. So the second method would make me write more code in that case. Logger is a singleton for the moment. My guess is that it will remain that way. What is the more 'beautiful' of the two and why? What is the usual practice?
EDIT:
What if this class was not named Logger? :). I have a Builder also. How about then?
I don't see what extra advantage approach two has over one (even considering unit testing!), infact with two, you have to ensure that everywhere you call a particular method, a Logger is available to pass in - and that could make things complicated...
Once you construct an object with the logger, do you really see the need to change it? If not, why bother with approach two?
I prefer the second method as it allows for more robust black box testing. Also it makes the interface of the function clearer (the fact that it uses such a Logger object).
The first thing is to be sure that the Logger dependency is being provided by the user in either case. Presumably in the first case, the constructor for FileNameLoader takes a Logger& parameter?
In no case would I, under any circumstances, make the Logger a Singleton. Never, not ever, no way, no how. It's either an injected dependency, or else have a Log free function, or if you absolutely must, use a global reference to a std::ostream object as your universal default logger. A Singleton Logger class is a way of creating hurdles to testing, for absolutely no practical benefit. So what if some program does create two Logger objects? Why is that even bad, let alone worth creating trouble for yourself in order to prevent? One of the first things I find myself doing, in any sophisticated logging system, is creating a PrefixLogger which implements the Logger interface but prints a specified string at the start of all messages, to show some context. Singleton is incompatible with with this kind of dynamic flexibility.
The second thing, then, is to ask whether users are going to want to have a single FileNameLoader, and call LoadFileNames on it several times, with one logger the first time and another logger the second time.
If so, then you definitely want a Logger parameter to the function call, because an accessor to change the current Logger is (a) not a great API, and (b) impossible with a reference member anyway: you'd have to change to a pointer. You could perhaps make the logger parameter a pointer with a default value of 0, though, with 0 meaning "use the member variable". That would allow uses where the users initial setup code knows and cares about logging, but then that code hands the FileNameLoader object off to some other code that will call LoadFileNames, but doesn't know or care about logging.
If not, then the Logger dependency is an invariant for each instance of the class, and using a member variable is fine. I always worry slightly about reference member variables, but for reasons unrelated to this choice.
[Edit regarding the Builder: I think you can pretty much search and replace in my answer and it still holds. The crucial difference is whether "the Builder used by this FileNameLoader object" is invariant for a given object, or whether "the Builder used in the call" is something that callers to LoadFileNames need to configure on a per-call basis.
I might be slightly less adamant that Builder should not be a Singleton. Slightly. Might.]
In general I think less arguments equals better function. Typically, the more arguments a function has, the more "common" the function tends to become - this, in turn, can lead to large complicated functions that try to do everything.
Under the assumption that the Logger interface is for tracing, in this case I doubt the the user of the FileNameLoader class really wants to be concerned with providing the particular logging instance that should be used.
You can also probably apply the Law of Demeter as an argument against providing the logging instance on a function call.
Of course there will be specific times where this isn't appropriate. General examples might be:
For performance (should only be done after identification of specific performance issues).
To aid testing through mock objects (In this case I think a constructor is a more appropriate location, for logging remaining a singleton is probably a better option...)
I would stick with the first method and use the Logger as a singleton. Different sinks and identifying where data was logged from is a different problem altogether. Identifying the sink can be as simple or as complex as you want. For example (assuming Singleton<> is a base-class for singletons in your code):
class Logger : public Singleton<Logger>
{
public:
void Log(const std::string& _sink, const std::string& _data);
};
Your class:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader& _pluginLoader)
{
Logger.getSingleton().Log("FileNameLoader", "loading xyz");
};
virtual ~FileNameLoader(){}
};
You can have an inherently complex Log Manager with different sinks, different log-levels different outputs. Your Log() method on the log manager should support simple logging as described above, and then you can allow for more complex examples. For debugging purposes, for example, you could define different outputs for different sinks as well as having a combined log.
The approach to logging that I like best is to have a member of type Logger in my class (not a reference or pointer, but an actual object).
Depending on the logging infrastructure, that makes it possible to decide, on a per-class basis, where the output should go or which prefix to use.
This has the advantage over your second approach that you can't (accidentally) create a situation where members of the same class can not be easily identified as such in the logfiles.

Advice on wrapping third party libraries

I have been working a year now as a software developer for a at the computer-vision department of a company. My main job is integration of third-party software into a framework, so i usually end up writing wrapper libraries because a lot of this third party software does not work the way we want it to work(not thread safe, pain in the a** to use etc.).
Normally i just wrap the whole library and guard the calls to the library with mutual exclusions(thread safety is somehow the major problem with most extern libraries). I really enjoy doing this, as it puts you into a lot of interesting situations and you get to see a lot of interesting code. However i often think that i am not doing it properly or that my implementation is not really good. I feel like i am lacking some sort of design knowledge on how to properly do stuff like that.
Basically i want to know if there are any good guidelines or hints about designing a proper 'API ontop of broken API', or if this is always bound to be quite hackish and ugly.
I will quote an answer to another question on here the other day:
Does your current method pass testing?
Is it fast enough?
If yes, keep doing what you are doing.
As an alternative
Just ensure your new API encompasses both the intended functionality and the conventional or accidental functionality of the original. Also ensure it presents a 'fit-for-purpose' re-presentation. Take a peek at the C++ wrapping of C libraries in FOSS projects such as GTK/GTK for C++ (which just wraps the former).
If the API is broken, fix it and submit a patch ... get involved with the third-parties (I am assuming having access to the source means they won't mind this) ... You could re-write some of their API to be 'wrapping friendly' and suggest they merge some changes. If there is a problem, be the one to fix it.
Not much to it, just wrap A with B and ensure B does what A was supposed to, or is used for.
The only thing that I can add to Aiden's response is that you should also look to replace code that requires explicit initialization and termination with RAII techniques. When I've been faced with providing a façade over APIs, I always seem to run into a class that looks like:
struct ADVERTISER {
/* a bunch of members here */
};
void adv_Initialize(ADVERTISER *adv, /* a bunch of arguments */);
void adv_DoStuff(ADVERTISER *adv);
void adv_Terminate(ADVERTISER *adv);
I've seen this wrapped in a C++ class in the following manner:
namespace wrapper {
class Advertiser {
public:
Advertiser(): inited_(false) {}
void initialize(/* a bunch of arguments */) {
terminate();
adv_Initialize(&adv_, ...);
inited_ = true;
}
void doStuff() {
validate();
adv_DoStuff(&adv_);
}
void terminate() {
if (inited_) {
adv_Terminate(&adv_);
inited_ = false;
}
}
protected:
void validate() {
if (!inited_) {
throw std::runtime_error("instance is not valid");
}
}
private:
ADVERTISER adv_;
bool inited_;
};
}
The problem is that the Advertiser class doesn't really make the API any easier to use or even cleaner IMHO. If you run into cases like this, then:
Use a fully parameterized constructor to ensure that invalid instances do not exist
Clean up all resources in the destructor
Write a copy constructor and assignment operator if they make sense or make them private and don't implement them.
My goal is to make sure that whatever API I am presenting/creating/wrapping works with our existing coding style. I also try to bend the API into a more OO style than it may currently be in. I have seen a number of what I call object-oriented C like the one that I presented above. If you want to make them really fit into C++, then make then truly object-oriented and take advantage of what C++ gives you:
Be careful to manage any state variables.
If actions like copying don't make sense, then hide them.
If there is any possibility of leaking resources, then find some way to prevent it from happening (usually employing RAII helps).
Restrict the creation of instances using constructors to eliminate invalid instances and other edge cases.

What's the proper "C++ way" to do global variables?

I have a main application class, which contains a logger, plus some general app configurations, etc.
Now I will display a lot of GUI windows and so on (that will use the logger and configs), and I don't want to pass the logger and configurations to every single constructor.
I have seen some variants, like declaring the main class extern everywhere, but that doesn't feel very object oriented. What is the "standard" C++ way to make elements in the main class accessible to all (or most) other classes?
Use the singleton design pattern.
Basically you return a static instance of an object and use that for all of your work.
Please see this link about how to use a singleton and also this stackoverflow link about when you should not use it
Warning: The singleton pattern involves promoting global state. Global state is bad for many reasons.
For example: unit testing.
It is not so bad idea to pass the logger and config to all the constructors if your logger and config is abstract enough.
Singleton can be a problem in the future. But it seams like a right choice in the project begin. Your choice. If your project is small enough - go with singleton. If not - dependency injection.
Why not use the system that's already in place? That is, redirect std::clog to output to a file and write to std::clog.
std::fstream *f = new std::fstream("./my_logfile.log")
std::clog.rdbuf(f->rdbuf());
std::clog << "Line of log information" << std::endl;
I'd agree with some kind of singleton approach. You definitely don't want to pass logger objects around all over the place. That will get very boring very quickly, and IMHO is a worse design than just having a plain global object.
A good test of whether you've got a good solution is the steps required to get the logging working in a function that needs it.
If you have to do much more than
#include "Logger.h"
...
void SomeFunction()
{
...
LOGERROR << "SomeFunction is broken";
...
}
...
then you are wasting effort.
Logging falls under the realm of 'separation of concern' as in aspect orient programming
Generally logging is not a function or concern of an object (for example, it does not change the state of the object; it is merely a mechanism for observing/recording the state, and the output is essentially disposable in most contexts)
It is an ephemeral and often optional side function that does not contribute to the operation of a class.
An object's method may perform logging, but the logging may be done there because it is a convenient place to do it or that point in the code execution stream is where one desires the state to be recorded.
Because C++ does not provide facilities for defining aspects, I tend to simply keep essentially external ephemeral objects like loggers global and wrap them in a namespace to sort of contain them. Namespaces are not intended for containment so this is kind of ugly, but for for lack of anything else it is convenient and is far less ugly and inconvienent than passing loggers in formal parameters or referencing them in all the objects you want to log. This also makes it easier to remove the logger if at some point I decide I no longer need the logger (I.e. if it was only used for debugging).
Don't know if this is helpful in your situation or not, but in MFC, there was/is an application class.
I use to throw things like this into that class.
I assume you are not using MFC, but if you have an application class or something similar, this might be helpful.
Why not use log4cxx?
Such problems are solved long ago and widely used by many.
Unless you're building some very special logging system of your own... In such case, I'd use Factory pattern which would create loggers for anyone interested (or giving away existing instance if it's singleton). Other classes would use factory to obtain the logger. Passing loggers in constructor parameters is a bad idea, because it couples your class with logger.
Why has no one thought of heritage and polymorphism? You could also use an abstract factory with that singleton ;)
Simply pass your main class into the constructor of the other classes that you want to have access to "everything"
Then you can provide access to the logger etc. via member properties.
(Forgive my C++ syntax, this is just a made-up language called "C++ confused by VB")
e.g.
Class App {
Private m_logger;
Private m_config;
Public logger() {
return m_logger;
}
Public config() {
return m_config
}
}
Class Window1 {
New( anApp ) {
}
....
}
I guess Service Locator will do. That you'll have to either pass around in constructors, or have a globally accessible static member function in some well-known location. The former option is much more preferable.
I would avoid the singleton pattern.
Too many problems when it comes to testing and all that (see What is so bad about singletons?)
Personally I would pass the logger etc into the constructor. Alternatively you can use a factory to create/pass a reference to the resource.

Treating classes as first-class objects

I was reading the GoF book and in the beginning of the prototype section I read this:
This benefit applies primarily to
languages like C++ that don't treat
classes as first class objects.
I've never used C++ but I do have a pretty good understanding of OO programming, yet, this doesn't really make any sense to me. Can anyone out there elaborate on this (I have used\use: C, Python, Java, SQL if that helps.)
For a class to be a first class object, the language needs to support doing things like allowing functions to take classes (not instances) as parameters, be able to hold classes in containers, and be able to return classes from functions.
For an example of a language with first class classes, consider Java. Any object is an instance of its class. That class is itself an instance of java.lang.Class.
For everybody else, heres the full quote:
"Reduced subclassing. Factory Method
(107) often produces a hierarchy of
Creator classes that parallels the
product class hierarchy. The Prototype
pattern lets you clone a prototype
instead of asking a factory method to
make a new object. Hence you don't
need a Creator class hierarchy at all.
This benefit applies primarily to
languages like C++ that don't treat
classes as first-class objects.
Languages that do, like Smalltalk and
Objective C, derive less benefit,
since you can always use a class
object as a creator. Class objects
already act like prototypes in these
languages." - GoF, page 120.
As Steve puts it,
I found it subtle in so much as one
might have understood it as implying
that /instances/ of classes are not
treated a first class objects in C++.
If the same words used by GoF appeared
in a less formal setting, they may
well have intended /instances/ rather
than classes. The distinction may not
seem subtle to /you/. /I/, however,
did have to give it some thought.
I do believe the distinction is
important. If I'm not mistaken, there
is no requirement than a compiled C++
program preserve any artifact by which
the class from which an object is
created could be reconstructed. IOW,
to use Java terminology, there is no
/Class/ object.
In Java, every class is an object in and of itself, derived from java.lang.Class, that lets you access information about that class, its methods etc. from within the program. C++ isn't like that; classes (as opposed to objects thereof) aren't really accessible at runtime. There's a facility called RTTI (Run-time Type Information) that lets you do some things along those lines, but it's pretty limited and I believe has performance costs.
You've used python, which is a language with first-class classes. You can pass a class to a function, store it in a list, etc. In the example below, the function new_instance() returns a new instance of the class it is passed.
class Klass1:
pass
class Klass2:
pass
def new_instance(k):
return k()
instance_k1 = new_instance(Klass1)
instance_k2 = new_instance(Klass2)
print type(instance_k1), instance_k1.__class__
print type(instance_k2), instance_k2.__class__
C# and Java programs can be aware of their own classes because both .NET and Java runtimes provide reflection, which, in general, lets a program have information about its own structure (in both .NET and Java, this structure happens to be in terms of classes).
There's no way you can afford reflection without relying upon a runtime environment, because a program cannot be self-aware by itself*. But if the execution of your program is managed by a runtime, then the program can have information about itself from the runtime. Since C++ is compiled to native, unmanaged code, there's no way you can afford reflection in C++**.
...
* Well, there's no reason why a program couldn't read its own machine code and "try to make conclusions" about itself. But I think that's something nobody would like to do.
** Not strictly accurate. Using horrible macro-based hacks, you can achieve something similar to reflection as long as your class hierarchy has a single root. MFC is an example of this.
Template metaprogramming has offered C++ more ways to play with classes, but to be honest I don't think the current system allows the full range of operations people may want to do (mainly, there is no standard way to discover all the methods available to a class or object). That's not an oversight, it is by design.