Search code examples
c++interfacehideimplementation

Hiding specific implementation of C++ interface


I'm relatively new to the more advanced C++ features... So keep that in mind ;)

I have recently defined an Interface to some class, consisting, of course, of only pure virtual functions.

Then, I implemented a specific version of that interface in separate files.

The question is... How do I invoke the specific implementation of that Interface on the user-end side, without revealing the internals of that specific implementation?

So if I have an Interface.h header file that looks like this:

class Interface
{
  public:
    Interface(){};
    virtual ~Interface(){};
    virtual void InterfaceMethod() = 0;
}

Then, a specific Implementation.h header file that looks like this:

class Implementation : public Interface
{
  public:
    Implementation(){};
    virtual ~Implementation(){};
    void InterfaceMethod();
    void ImplementationSpecificMethod();
}

Finally, under main, I have:

int main()
{
  Interface *pInterface = new Implementation();
  // some code
  delete pInterface;
  return 0;
}

How can I do something like this, without revealing the details of Implementation.h, from "main"? Isn't there a way to tell "main"... Hey, "Implementation" is just a type of "Interface"; and keep everything else in a separate library?

I know this must be a duplicate question... But I couldn't find a clear answer to this.

Thanks for the help!


Solution

  • You can use a factory.

    Header:

    struct Abstract
    {
        virtual void foo() = 0;
    }
    
    Abstract* create();
    

    Source:

    struct Concrete : public Abstract
    {
        void foo() { /* code here*/  }
    }
    
    Abstract* create()
    {
        return new Concrete();
    }