I didn't figure out a better title for the question. Let me explain it better now:
The project I am working on is going to connect to a remote server, encrypt the session and send/receive data packets.
I'd like to make it modular enough, so I thought it'd be nice to use 3 distinct classes. These would be:
1) A socket wrapper class with some virtual methods such as OnReceivedData() and OnConnected().
2) An inherited class of the socket wrapper, implementing the encryption of data before it is sent and decrypting data on its arrival.
3) The main object itself, which should override any one of the above classes depending upon its need to be encrypted or not, so it could receive the OnReceivedData() and OnConnected() events notification as well and act based upon it.
So the problem is HOW do I make my program to know it has to first call the event on the encryption object and then call that same event on the main object? Because I guess if I override the socket wraper with the encryption and then override the encryption with the main object, it will probably just call the main object method (it would call the OnReceivedData() directly on the main object, not passing through the decryption object first, right?).
Is this called multiple inheritance?
BTW if you think it is a bad project design, I would appreciate any better approaches.
Thank you for taking your time to read this.
Don't make the encryption object a descendant. Make it a decorator or proxy. The main object shouldn't need to know whether it's encrypting things. Instead, it will have a data-transfer object (the socket class) that sends and receives data, and if that data-transfer object happens to be something that encrypts the data before passing it along to the real socket object, so be it. That's no concern of the main object.
With a proxy, the encryption class would have the same interface as the socket object. It would wrap the socket object, and the main object would talk to the socket through the encryption object. If you don't want encryption, then assign the socket object to the main object directly and skip the middle-man.
With a decorator, the main object would talk directly to the socket object, but the socket object would run everything through the encryption object before sending it along the wire. If there is no decorator set, then the socket object would send the data directly instead.
Decorators and proxies are covered in Fowler's Design Patterns, which includes examples in C++.
It is not called multiple inheritance (this is when one class inherits from multiple super classes). It is called method overriding. In your 'main' OnReceivedData, you can explicitly call the 'super' method by qualifying its name, EncryptedBaseClass::OnReceivedData().
This can become messy. What I would recommend is that you invert the ownership and let the encryption class hold a reference to the socket class, in line with the decorator pattern (Having an encryption decorator). This will resolve your override problems while still provide you with the functionality that you seek.
Related
I'm using the standard C/C++ socket function, but I'd like to encapsulate them into a C++ class. The problem is that the functions for sending and receive returns (or require) pointers to void. Is there any way to use an object that encapsulates those values?
For example, in Java the Socket class uses both ObjectOutputStream and ObjectInputStream in order to work with Object type so every object can be sent via Sockets.
I know that in Java the approach is quite different because the pointers are hidden to the programmer, but is there any similar solution in C++?
socket isn't a c++ function. It's a system level function and it doesn't know anything about objects (or indeed anything in c++), so you have to arrange to provide it with a pointer to the data you want transferred.
As #GCT says, socket isn't a function but is a system level function which is used to handle network connections. In C/C++ each socket is identified with an Integer value, so it's not easy, as you want, to handle it as an object.
I recommend you to read this tutorial to know more about socket.
Maybe it can help you: I have a project that show how to use sockets in C++. Server and client are contained in their own class. You can get it by this link.
I have a multithreading C++ design question for Windows. Suppose I have a C++ class as follows:
class CCamera_AxisNew : public CCamera_IPBase64 and suppose in the base class, CCamera_IPBase64, implementation of PTZThreadProc(..) , I read commands from a queue and asynchronously send PTZ commands only through either
the object pointer indirectly, IPTZControl->SetProperty(..) where the object pointer IPTZControl = new CCamera_AxisNew or other similar constructors or
directly through this->SetProperty()
The method PTZThreadProc(..) is spawned on a separate thread.
Also, in the class CCamera_IPBase64, I can bypass the PTZThreadProc(..) which runs on a separate thread by synchronously sending non-PTZ commands through either
the object pointer indirectly, IPTZControl->WriteCamera(...), or
directly through this->WriteCommand(..).
The client program sends requests through a REST endpoint to an CCamera_IPBase64 object which uses a main thread to receive the request and places only PTZ commands on a queue.
My question is it better to use delegation IPTZControl->SetProperty(..) or avoid delegation such as this->SetProperty()
Any help is greatly appreciated.
It is better to avoid delegation by using this->SetProperty() and taking advantage of inheritance since it avoids extra redundant code required by the delegation design pattern.
I have been working with boost::asio for a while now and while I do understand the concept of the asynchronous calls I am still somewhat befuddled by the memory management implications. In normal synchrous code the object lifetime is clear. But consider a scenario similar to the case of the daytime server:
There might be multiple active connections which have been accepted. Each connection now sends and receives some data from a socket, does some work internally and then decides to close the connection. It is safe to assume that the data related to the connection needs to stay accessible during the processing but the memory can be freed as soon as the connection is closed. But how can I implement the creation/destruction of the data correctly? Assuming that I use classes and bind the callback to member functions, should I create a class using new and call delete this; as soon as the processing is done or is there a better way?
But how can I implement the creation/destruction of the data correctly?
Use shared_ptr.
Assuming that I use classes and bind the callback to member functions, should I create a class using new and call delete this; as soon as the processing is done or is there a better way?
Make your class inherit from enable_shared_from_this, create instances of your classes using make_shared, and when you bind your callbacks bind them to shared_from_this() instead of this. The destruction of your instances will be done automatically when they have gone out of the last scope where they are needed.
I have a singleton class for logging purpose in my Qt project. In each class except the singleton one, there is a pointer point to the singleton object and a signal connected to an writing slot in the singleton object. Whichever class wants to write log info just emit that signal. The signals are queued so it's thread-safe.
Please critique this approach from OOP point of view, thanks.
=============================================================================================
Edit 1:
Thank you all your applies, listening to opposite opinions is always a big learning.
Let me explain more about my approach and what I did in my code so far:
Exactly as MikeMB pointer, the singleton class has a static function like get_instance() that returns a reference to that singleton. I stored it in a local pointer in each class's constructor, so it will be destroyed after the constructor returns. It is convenient for checking if I got a null pointer and makes the code more readable. I don't like something as this:
if(mySingletonClass::gerInstance() == NULL) { ... }
connect(gerInstance(), SIGNAL(write(QString)), this, SLOT(write(QString)));
because it is more expensive than this:
QPointer<mySingletonClass> singletonInstance = mySingletonClass::getInstance();
if(singletonInstance.isNull) { ... }
connect(singletonInstance, SIGNAL(write(QString)), this, SLOT(write(QString)));
Calling a function twice is more expensive than creating a local variable from ASM's point of view because of push, pop and return address calculation.
Here is my singleton class:
class CSuperLog : public QObject
{
Q_OBJECT
public:
// This static function creates its instance on the first call
// and returns it's own instance just created
// It only returns its own instance on the later calls
static QPointer<CSuperLog> getInstance(void); //
~CSuperLog();
public slots:
void writingLog(QString aline);
private:
static bool ready;
static bool instanceFlag;
static bool initSuccess;
static QPointer<CSuperLog> ptrInstance;
QTextStream * stream;
QFile * oFile;
QString logFile;
explicit CSuperLog(QObject *parent = 0);
};
I call getInstance() at the beginning of main() so make sure it is read immediately for each other class whenever they need to log important information.
MikeMB:
Your approach is making a middle man sitting in between, it makes the path of the logging info much longer because the signals in Qt are always queued except you make direct connection. The reason why I can't make direct connection here is it make the class non-thread-safe since I use threads in each other classes. Yes, someone will say you can use Mutex, but mutex also creates a queue when more than one thread competing on the same resource. Why don't you use the existing mechanism in Qt instead of making your own?
Thank you all of your posts!
=========================================================
Edit 2:
To Marcel Blanck:
I like your approach as well because you considered resource competition.
Almost in every class, I need signals and slots, so I need QObject, and this is why I choose Qt.
There should be only one instance for one static object, if I didn't get it wrong.
Using semaphores is same as using signals/slots in Qt, both generates message queue.
There always be pros and cons regarding the software design pattern and the application performance. Adding more layers in between makes your code more flexible, but decreases the performance significantly on those lower-configured hardware, making your application depending one most powerful hardware, and that's why most of modern OSes are written in pure C and ASM. How to balance them is really a big challenge.
Could you please explain a little bit more about your static Logger factory approach? Thanks.
I do not like singletons so much because it is always unclean to use them. I have even read job descriptions that say "Knowledge of design patterns while knowing that Singleton isn't one to use". Singleton leads to dependecy hell and if you ever want to change to a completely different logging approach (mabe for testing or production), while not destroying the old one you, need to change a lot.
Another problem with the approch is the usage of signals. Yes get thread savety for free, and do not interrupt the code execution so much but...
Every object you log from needs to be a QObject
If you hunt crashes your last logs will not be printed because the logger had no time to do it before the program crashed.
I would print directly. Maybe you can have a static Logger factory that returns a logger so you can have one logger object in every thread (memory impact will still be very small). Or you have one that is threadsave using semaphores and has a static interface. In both cases the logger should be used via an interface to be more flexible later.
Also make sure that your approach prints directly. Even printf writes to a buffer before being printed and you need to flush it every time or you might never find crashes under bad circumstances, if hunting for them.
Just my 2 cents.
I would consider separating the fact that a logger should be unique, and how the other classes get an instance of the logger class.
Creating and obtaining an instance of the logger could be handled in some sort of factory that internally encapsulates its construction and makes only one instance if need be.
Then, the way that the other classes get an instance of the logger could be handled via Dependency injection or by a static method defined on the aforementioned factory. Using dependency injection, you create the logger first, then inject it into the other classes once created.
A singleton usually has a static function like get_instance() that returns a reference to that singleton, so you don't need to store a pointer to the singleton in every object.
Furthermore it makes no sense, to let each object connect its log signal to the logging slot of the logging object itself, because that makes each and every class in your project dependent on your logging class. Instead, let a class just emit the signal with the log information and establish the connection somewhere central on a higher level (e.g. when setting up your system in the main function). So your other classes don't have to know who is listening (if at all) and you can easily modify or replace your logging class and mechanism.
Btw.: There are already pretty advanced logging libraries out there, so you should find out if you can use one of them or at least, how they are used and adapt that concept to your needs.
==========================
EDIT 1 (response to EDIT 1 of QtFan):
Sorry, apparently I miss understood you because I thought the pointer would be a class member and not only a local variable in the constructor which is of course fine.
Let me also clarify what I meant by making the connection on a higher level:
This was solely aimed at where you make the connection - i.e. where you put the line
connect(gerInstance(), SIGNAL(write(QString)), this, SLOT(write(QString)));
I was suggesting to put this somewhere outside the class e.g. into the main function. So the pseudo code would look something like this:
void main() {
create Thread1
create Thread2
create Thread3
create Logger
connect Thread1 signal to Logger slot
connect Thread2 signal to Logger slot
connect Thread3 signal to Logger slot
run Thread1
run Thread2
run Thread3
}
This has the advantage that your classes don't have to be aware of the kind of logger you are using and whether there is only one or multiple or no one at all. I think the whole idea about signals and slots is that the emitting object doesn't need to know where its signals are processed and the receiving class doesn't have to know where the signals are coming from.
Of course, this is only feasible, if you don't create your objects / threads dynamically during the program's run time. It also doesn't work, if you want to log during the creation of your objects.
I've been bashing my head for the last two nights trying to figure this out with no positive results. There is the thing, in boost signals, every time I want to connect, say, a member function of one class to another's class signal, I have to save the resulting connection in a variable if I want to disconnect later. If later on, I want to connect the same member function to some other class signal (the member function is still connected with the previous class signal) I have to save this new connection in order to manage it too. My question is, is there any way to avoid this?
You shouldn't need to keep connection instances around, you should be able to disconnect from a signal by passing the original callable to signal::disconnect, as described in the Boost.Signals tutorial. With member functions the problem is rather the fact that you cannot pass them directly to signal, you either wrap them in custom function objects, which would then be available as arguments to signal::disconnect or you use Boost.Bind, which by itself wouldn't be very useful as you cannot conveniently declare its return type. However that problem can be solved using Boost.Bind together with Boost.Function.
I hope I answered your question.
Scoped Connections
Alternatively you could assign the returned connection to a variable of type signal::scoped_connection. It's a type of connection which automatically disconnects on destruction or reassignment. This effectively limits a signal-slot connection lifetime to a particular scope.
For example when you reassign myConnection, the previous connection is automatically disconnected:
scoped_connection myConnection = someObject.Signal.connect(MyHandler);
myConnection = totallyDifferentObject.Signal.connect(MyHandler);
Automatic Connection Management
In our project, we usually declare member variables as scoped connections. So their scope matches the live time of the particular object instance the belong to. This is a convenient way to automatically disconnect any signals an object instance is connected to when it is being destructed. Without scoped connections you have to manually disconnect yourself in the destructor. If you neglect to disconnect instances when they're destroyed, you'll end up invoking invalid signal handlers which will crash your programs.