Wrapper design pattern - c++

Say I have a class:
class B;
class A{
public:
A();
virtual B foo();
}
defined in a 3rd party component. I want to wrap classes A and B, resulting myA and myB.
Now, I shouldn't be able to access class A and class B from the outside, but rather have the same functionality for myA and myB. foo() could be called from the 3rd party module.
I would prefer to do this using inheritence, not encapsulation.
So there are 2 problems:
Calling a->myFoo() (need to rename methods because of same signature and different return type) should call A::foo() if a is of type myA.
Calling a->myFoo() should call myA2::myFoo() if a is of type class myA2::myA.
Any suggestions on how to do this elegantly? I came up with some solutions but I prefer a fresh view on the whole thing.
EDIT:
Just a theoretical question. I don't actually need to do this, just thinking of ways it can be achieved.
EDIT2:
myA2 is a class that extends myA. Before the pattern, it would have been called A2 (a class that extended the class A from the 3rd party module).

I don't understand why you prefer to do this with inheritance instead of encapsulation. Generally speaking, extending the class you're wrapping is the "wrong" way to implement the wrapper pattern, especially since you generally want to redefine the interface in the process. In class myA, you'll have a field of type A that contains an instance of class A, which methods in myA can call upon as needed. Unless I've misunderstood what you want to accomplish, this is the most elegant way to accomplish what you want.

You should be able to declare the function names/parameters similarly. Check out:
strange-inheritance section: [23.9] What's the meaning of, Warning: Derived::f(char) hides Base::f(double)? on the 3rd code block.
It also shows the syntax for calling base methods.

Related

Why define Parent class as friend class?

I am looking at other's code and find one part I can't understand.
class a {
public:
function xxx () {.....}
}
class b : public a {
public:
xxxx
protected:
constructor()....
friend class a ; <= here why it is needed ????
}
As I understand, since b had already inherited from a, it should be able to use the function of a directly. What's the purpose of this "friend" declaration used for?
The friend allows a to use b's methods, not the other way around, which isn't implicit.
The design looks fishy though, a base class shouldn't care about derived classes.
friend class a; grants class a the right to access non-public members of b. So in this small example, an instance of a can call b::constructor(). Without friendship, it wouldn't be possible.
As to why, there is not enough information to answer that, other than there must be a need for instances of a to call b::constructor() (assuming that to be anything other than the syntax error it currently is).
As I understand, since b had already inherited from a, it should be able to use the function of a directly.
Yes. The friend specification though allows access the other way around (instances of a will be able to access private data and functions of b).
What's the purpose of this "friend" declaration used for?
The example above doesn't suggest any. The only situation where it may make sense is with using CRTP in certain situations (i.e. a is a template of b) but even so, if you see such a requirement ("must add friend declaration in b") it is possible that the design you're looking at is flawed.
Can you post a concrete example?
Depending on your projects/requirements, your class designs change. I have no comment on your class hierarchy but true your question is all about theories of friend usage. If you don't use friend, you will not be able to call B members from A. It is there for...cross-mating :D
It almost certainly means that there is a serious design problem. One of the basic rules of thumb for inheritance is that base classes should not need any information about derived classes. Making a a friend of b makes it possible for member functions of a to get at the internals of b objects.

C++ inheritance pattern

I am after your opinion on how best to implement an inheritance pattern in C++. I have two base classes, say
class fooBase{
protected:
barBase* b;
};
class barBase{};
where fooBase has a barBase. I intend to put these classes in a library, so that wherever I have a fooBase it can use its barBase member.
I now intend to create a specialisation of these in a specific program
class fooSpec : public fooBase{};
class barSpec : public barBase{};
Now I want fooSpec::b to point to a barSpec instead of a barBase. I know that I can just initialise b with a new barSpec, but this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
Is there another way that this is often acheived?
Cheers.
Create a method in your specclass to cast the b into the special version.
That way instead of casting it all the time, it looks like a getter.
On the other hand OO is about programming towards interfaces and not objects. So what you are doing here looks like programming towards objects. But the is difficult to see as this example is purely theoretical.
You may consider the template solution:
template <class T>
class fooBase{
protected:
T* b;
};
and then use it as
class fooSpec : public fooBase<barSpec>{};
while ordinarily, the base would be used as fooBase<barBase>.
Is this what you want?
Normally we create a function that has the cast and returns the pointer -- and use that instead of the member directly.
Now I want fooSpec::b to point to a barSpec instead of a barBase.
There's no such thing as fooSpec::b. b belongs to fooBase, and your new class fooSpec is a (specialization of) a fooBase. You can't change the fact that b, a fooBase member, is of type barBase. This is a property of all the instances of fooBase that you can't invalidate in the particular subset of instances concerned by your specialization.
I know that I can just initialise b with a new barSpec, but this would
require me to cast the pointer to a barSpec whenever I wanted to use
specific functions in the specialisation wouldn't it?
Yes and no. Yes, you need to do that cast; but no, you don't need to do it every time. You can encapsulated in a function of fooSpec.
Is there another way that this is often acheived?
Not that I'm aware of.
this would require me to cast the pointer to a barSpec whenever I wanted to use specific functions in the specialisation wouldn't it?
That depends on whether the method you are trying to invoke is defined in the superclass and whether it is virtual.
You need to cast the pointer before invoking a method if one of the following is true...
The method belongs to the subclass only
The superclass has an implementation of the method and the subclass's implementation does not override the implementation in the superclass. This amounts to a question of whether the function is a virtual function.
Avoid data members in non-leaf classes, use pure virtual getters instead. If you follow this simple rule, your problem solves itself automatically.
This also makes most non-leaf classes automatically abstract, which may seem like an undue burden at first, but you get used to it and eventually realize it's a Good Thing.
Like most rules, this one is not absolute and needs to be broken now and then, but in general it's a good rule to follow. Give it a try.
If it looks too extreme, you may try one of the design patterns that deal with dual hierarchies such as Stairway to Heaven.

Is there any way to avoid declaring virtual methods when storing (children) pointers?

I have run into an annoying problem lately, and I am not satisfied with my own workaround: I have a program that maintains a vector of pointers to a base class, and I am storing there all kind of children object-pointers. Now, each child class has methods of their own, and the main program may or not may call these methods, depending on the type of object (note though that they all heavily use common methods of the base class, so this justify inheritance).
I have found useful to have an "object identifier" to check the class type (and then either call the method or not), which is already not very beautiful, but this is not the main inconvenience. The main inconvenience is that, if I want to actually be able to call a derived class method using the base class pointer (or even just store the pointer in the pointer array), then one need to declare the derived methods as virtual in the base class.
Make sense from the C++ coding point of view.. but this is not practical in my case (from the development point of view), because I am planning to create many different children classes in different files, perhaps made by different people, and I don't want to tweak/maintain the base class each time, to add virtual methods!
How to do this? Essentially, what I am asking (I guess) is how to implement something like Objective-C NSArrays - if you send a message to an object that does not implement the method, well, nothing happens.
regards
Instead of this:
// variant A: declare everything in the base class
void DoStuff_A(Base* b) {
if (b->TypeId() == DERIVED_1)
b->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
b->DoDerived12Stuff();
}
or this:
// variant B: declare nothing in the base class
void DoStuff_B(Base* b) {
if (b->TypeId() == DERIVED_1)
(dynamic_cast<Derived1*>(b))->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
(dynamic_cast<Derived2*>(b))->DoDerived12Stuff();
}
do this:
// variant C: declare the right thing in the base class
b->DoStuff();
Note there's a single virtual function in the base per stuff that has to be done.
If you find yourself in a situation where you are more comfortable with variants A or B then with variant C, stop and rethink your design. You are coupling components too tightly and in the end it will backfire.
I am planning to create many different children classes in different
files, perhaps made by different people, and I don't want to
tweak/maintain the base class each time, to add virtual methods!
You are OK with tweaking DoStuff each time a derived class is added, but tweaking Base is a no-no. May I ask why?
If your design does not fit in either A, B or C pattern, show what you have, for clairvoyance is a rare feat these days.
You can do what you describe in C++, but not using functions. It is, by the way, kind of horrible but I suppose there might be cases in which it's a legitimate approach.
First way of doing this:
Define a function with a signature something like boost::variant parseMessage(std::string, std::vector<boost::variant>); and perhaps a string of convenience functions with common signatures on the base class and include a message lookup table on the base class which takes functors. In each class constructor add its messages to the message table and the parseMessage function then parcels off each message to the right function on the class.
It's ugly and slow but it should work.
Second way of doing this:
Define the virtual functions further down the hierarchy so if you want to add int foo(bar*); you first add a class that defines it as virtual and then ensure every class that wants to define int foo(bar*); inherit from it. You can then use dynamic_cast to ensure that the pointer you are looking at inherits from this class before trying to call int foo(bar*);. Possible these interface adding classes could be pure virtual so they can be mixed in to various points using multiple inheritance, but that may have its own problems.
This is less flexible than the first way and requires the classes that implement a function to be linked to each other. Oh, and it's still ugly.
But mostly I suggest you try and write C++ code like C++ code not Objective-C code.
This can be solved by adding some sort of introspection capabilities and meta object system. This talk Metadata and reflection in C++ — Jeff Tucker demonstrates how to do this using c++'s template meta programming.
If you don't want to go to the trouble of implementing one yourself, then it would be easier to use an existing one such as Qt's meta object system. Note that this solution does not work with multiple inheritance due to limitations in the meta object compiler: QObject Multiple Inheritance.
With that installed, you can query for the presence of methods and call them. This is quite tedious to do by hand, so the easiest way to call such a methods is using the signal and slot mechanism.
There is also GObject which is quite simmilar and there are others.
If you are planning to create many different children classes in different files, perhaps made by different people, and also I would guess you don't want to change your main code for every child class. Then I think what you need to do in your base class is to define several (not to many) virtual functions (with empty implementation) BUT those functions should be used to mark a time in the logic where they are called like "AfterInseart" or "BeforeSorting", Etc.
Usually there are not to many places in the logic you wish a derived classes to perform there own logic.

What's the best way to access the internal data structure within a class?

I have a class A consisting of a bunch of internal data structures (e.g. m_data) and a few objects (e.g. ClassB):
class A
{
public:
...
private:
int m_data[255];
ClassB B[5];
}
What's the best way for B to access m_data? I don't want to pass m_data into B's function..
// updated:
Many thanks for the responses. Let me provide more contextual info.
I am working on an AI project, where I got some data (e.g. m_data[i]) at each time step. The class A needs to buffer these information (m_data) and uses a list of B's (example updated) to make inference. Class B itself is actually a base class, where different children derive from it for different purpose so I guess in this context, making B a subclass of A might not be clean (?)..
friend class ClassB;
Put this line anywhere in A's declaration if you want ClassB to access all of A's protected and private members.
One of:
Make ClassB a friend of A
Make A a sub-class of ClassB and make m_data protected rather than private
[In response to Mark B's comment]
If ever you feel the need to resort to a friend relationship, the design should be reconsidered - it may not be appropriate. Sub-classing may or may not make sense; you have to ask yourself "Is class A and kind of class ClassB?" If the question makes no sense intuitively, or the answer is just no, then it may be an inappropriate solution.
Ideally, you don't allow external access the data structure at all. You should rethink your approach, considering more the question "What are the functional requirements / use cases needed for ClassB to access instances of A" rather than offloading the management of the internal members to methods not managed within class A. You will find that restricting management of internal members to the class owning those members will yield cleaner code which is more easily debugged.
However, if for some reason this is not practical for your situation there are a couple possibilities that come to mind:
You can provide simple get/set accessor methods which, depending upon
your requirements, can be used to access either a copy of or a
reference to m_data. This has the disadvantage of allowing everybody
access, but does so only through well defined interfaces (which can
be monitored as needed).
ggPeti mentions use of friend, which may work for you, but it gives ClassB access to all of the internals of A.
A getData() function that returns m_data.
Use setData() to change the value.
So in the function in class B you would create a pointer to the class type A variable that you created. Lets just call this pointer 'p'.
Just do p->getData(), p.getData() may be the answer. I think they do the same thing but c++ uses the '->' and some other languages use the '.'. Don't quote me on that one though.
Good luck, sir. Hope I helped ya.
What's the best way for B to access m_data?
Depends on the use.
This is how would I do it :
class ClassB
{
// ...
void foo( A &a )
{
// use a's data
}
};
class A
{
//...
int m_data[255];
ClassB & B;
};
Depending on the implementation, maybe ClassB is not needed at all. Maybe it's methods can be converted to functions.

extend a abstract base class w/o source recompilation?

ignore this, i thought of a workaround involving header generation. It isnt the nicest solution but it works. This question is to weird to understand. Basically i want to call a virtual function that hasnt been declared in the lib or dll and use it as normal (but have it not implemented/empty func).
I have an abstract base class in my library. All my plugins inherit from it, the user plugin inherits from this class and his application uses this class as a plugin pointer. I want that user to be able to extend the class and add his functions. The problem is, I am sure if he adds a virtual function and try to call it, the code will crash due to my objects not having the extra data in its vtable. How can I work around that? I thought of inheriting it but that would lead to ugly problems when a 3rd user comes to play. I dont want him to typecast to send the extended functions.
I was thinking of a msg function like intptr_t sendMsg(enum msgName, void* argv); But that removes the safty and I'd need to typecast everything. Whats the best solution for this? I would much rather use vtables then use a sendMsg function. How can I work around this?
Are you asking if you can add virtual functions to the base class without recompiling? The short answer to that is "no". The long answer is in your question, you'd have to provide some kind of generic "call_func" interface that would allow you to call functions "dynamically".
I think you can use register and callback mechanism
Your plugin can provide
Abstract base class "Base" and function
Register(Base *);
Now client can call plugin Register function
Register(b);
where b is defined as
Base *b = new Derived;
where Derived is new class derived from Base
I am not 100% sure I see the problem.
If the user1 derived type extends your base class (with more virtual methods) then that should be fine (of course your code will never know or understand these new methods but presumably you would not be calling them:
class B
{
virtual void doStuff() { /* Nothing */}
};
// User 1 version:
class U1: public B
{
virtual void doStuff()
{
this->doA();
this->doB();
}
virtual void doA() {}
virtual void doB() {}
};
// User 2 version can extend it differently.
Note:
If you are worried by slicing because you are storing objects in a vector that is a slightly different problem.
std::vector<B> objs;
objs.push_back(U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));
Here the problem is that a user defined type U1 can not be copied into the vector because the vector holds only B objects. This slices off the extra data held in U1.
The solution to this problem is that you need to hold pointers in the vector. This of course leads to other problems with exception safety. So boost has the ptr_vector<> container to hold objects correctly but still let them be used like objects.
#include <boost/ptr_container/ptr_vector.hpp>
......
boost::ptr_vector<B> objs;
objs.push_back(new U1());
std::for_each(objs.begin(),objs.end(),std::mem_fun_ref(&B::doStuff));