I have some problems with virtual classes and encapsulation. Consider the following minimal example of a C++ program:
#include <iostream>
class IConnection
{
public:
virtual void connect() = 0;
virtual std::string recv() = 0;
virtual void disconnect() = 0;
virtual ~IConnection() {}
};
class ConcreteConnection: public IConnection
{
public:
ConcreteConnection(): m_connected(false) {}
void connect() { m_connected = true; }
std::string recv() { return "Received some text."; }
void disconnect() { m_connected = false; }
private:
bool m_connected;
};
class Container
{
public:
Container() { m_connection = NULL; }
void SetConnection(IConnection *connection) { m_connection = connection; };
void GetData() { std::cout << m_connection->recv() << std::endl; }
~Container() { delete m_connection; }
private:
IConnection *m_connection;
};
int main(void)
{
Container container;
ConcreteConnection *connection = new ConcreteConnection();
container.SetConnection(connection);
container.GetData();
return 0;
}
This simple example works fine, but I am not totally happy with that. The Container-object should own the connection, without being bothered by the concrete implementation of the interface IConnection. That's why I created the ConcreteConnection-object outside of the container. What I don't like is that I have to pass a pointer or reference of the connection. I would like to pass a copy of the connection-object, so that the main-function does not have any chance to manipulate or delete the connection-object after passing it to the container. But as far as I know it is impossible to pass a copy of the connection, without telling the container to which concrete implementation of IConnection it belongs.
So do you have any idea how to solve this? Is it somehow possible to pass a copy of an object to any function without telling the function to which specific implementation of an interface the object belongs to?
I'm relatively new to both C++ and OOP, so don't hesitate and tell me, if my class struct is completely wrong and this case does not occur in real-life programming code (and how it should work instead).
Thanks in advance.