Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class - hiding implementation in C++ practice

Tags:

c++

oop

Recently I've been writing code similar to this:

messagehandler.h:

#include "message.h"
class MessageHandler {
public:
   virtual ~MessageHandler() {}
   virtual void HandleMessage(Message *msg) = 0:
};

persistmessagehandler.h:

MessageHandler *CreatePersistMessageHandler();

persistmessagehandler.cpp:

#include "messagehandler.h"
#include "persist.h"

class PersistMessageHandler : public MessageHandler {
private:
   PersistHandle ph;
   size_t count;
   InternalCheck();
public:
   PersistMessageHandler(int someParam);
   virtual ~PersistMessageHandler ();
   virtual void HandleMessage(Message *msg):
};
PersistMessageHandler::PersistMessageHandler(int someParam)
{
  ph.Initialize();
}
... rest of implementation.

MessageHandler *CreatePersistMessageHandler(int someParam)
{
  return new PersistMessageHandler(someParam);
}

The reasoning here is to hide the PersistMessageHandler. Clients don't need to include a header for the PersistMessageHandler class, with all the includes and types the implementation might need, and to more cleanly seperate the interface and implementation. . It'll always be dynamically allocated anyway,

All PersistMessageHandler users will just call CreatePersistMessageHandler(..); directly or indirectly get one from a factory.

But. I've not seen this approach used much elsewhere. Is the above good practice ? Are there other/better alternatives for simple cases ?

like image 919
Anonym Avatar asked Jan 26 '10 09:01

Anonym


2 Answers

You always have to hide as much as possible. Your way (putting implementation classes into .cpp) is a common way to do this in c++.

like image 144
Mykola Golubyev Avatar answered Sep 22 '22 00:09

Mykola Golubyev


This is a good way to hide implementation details from your clients. If you are working in Windows, you might also consider using an __interface instead of an abstract base class.

An Interface is an MSVC compiler extension that looks like an abstract base class, but has different rules for creation and destruction than a normal c++ class. It's the standard way of working in Windows, so there are system supported facilities for working with out-of-process objects and for using them in .NET code.

like image 31
John Knoeller Avatar answered Sep 18 '22 00:09

John Knoeller