Let's say I have pure abstract class IHandler
and my class that derives from it:
class IHandler
{
public:
virtual int process_input(char input) = 0;
};
class MyEngine : protected IHandler
{
public:
virtual int process_input(char input) { /* implementation */ }
};
I want to inherit that class in my MyEngine so that I can pass MyEngine*
to anyone expecting IHandler*
and for them to be able to use process_input
.
However I don't want to allow access through MyEngine*
as I don't want to expose implementation details.
MyEngine* ptr = new MyEngine();
ptr->process_input('a'); //NOT POSSIBLE
static_cast<IHandler*>(ptr)->process_input('a'); //OK
IHandler* ptr2 = ptr; //OK
ptr2->process_input('a'); //OK
Can this be done via protected inheritance and implicit casting? I only managed to get:
conversion from 'MyEngine *' to 'IHandler *' exists, but is inaccessible
Since I come from C# background, this is basically explicit interface implementation in C#. Is this a valid approach in C++?
Additional:
To give a better idea why I want to do this, consider following:
Class TcpConnection
implements communication over TCP, and in its constructor expects pointer to interface ITcpEventHandler
.
When TcpConnection
gets some data on a socket, it passes that data to its ITcpEventHandler
using ITcpEventHandler::incomingData
, or when it polls for outgoing data it uses ITcpEventHandler::getOutgoingData
.
My class HttpClient
uses TcpConnection
(aggregation) and passes itself to TcpConnection
constructor, and does processing in those interface methods.
So TcpConnection
has to implement those methods, but I don't want users using HttpClient
to have direct access to ITcpEventHandler
methods (incomingData
, getOutgoingData
). They should not be able to call incomingData
or getOutgoingData
directly.
Hope this clarifies my use case.