Logo Questions Linux Laravel Mysql Ubuntu Git Menu

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
    virtual ~Interface(){};
    virtual void InterfaceMethod() = 0;

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

class Implementation : public Interface
    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!

like image 430
ThermoX Avatar asked Mar 12 '23 20:03


1 Answers

You can use a factory.


struct Abstract
    virtual void foo() = 0;

Abstract* create();


struct Concrete : public Abstract
    void foo() { /* code here*/  }

Abstract* create()
    return new Concrete();
like image 143
Ivan Rubinson Avatar answered Mar 21 '23 06:03

Ivan Rubinson