Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use a C++ Interface

Tags:

c++

interface

I have an interface class similar to:

class IInterface
{
public:

    virtual ~IInterface() {}

    virtual methodA() = 0;

    virtual methodB() = 0;

};

I then implement the interface:

class AImplementation : public IInterface
{
    // etc... implementation here
}

When I use the interface in an application is it better to create an instance of the concrete class AImplementation. Eg.

int main()
{
    AImplementation* ai = new AIImplementation();
}

Or is it better to put a factory "create" member function in the Interface like the following:

class IInterface
{
public:

    virtual ~IInterface() {}

    static std::tr1::shared_ptr<IInterface> create(); // implementation in .cpp
    virtual methodA() = 0;

    virtual methodB() = 0;

};

Then I would be able to use the interface in main like so:

int main()
{
    std::tr1::shared_ptr<IInterface> test(IInterface::create());
}

The 1st option seems to be common practice (not to say its right). However, the 2nd option was sourced from "Effective C++".

like image 796
Seth Avatar asked Jul 29 '09 04:07

Seth


1 Answers

One of the most common reasons for using an interface is so that you can "program against an abstraction" rather then a concrete implementation.

The biggest benefit of this is that it allows changing of parts of your code while minimising the change on the remaining code.

Therefore although we don't know the full background of what you're building, I would go for the Interface / factory approach.

Having said this, in smaller applications or prototypes I often start with concrete classes until I get a feel for where/if an interface would be desirable. Interfaces can introduce a level of indirection that may just not be necessary for the scale of app you're building.

As a result in smaller apps, I find I don't actually need my own custom interfaces. Like so many things, you need to weigh up the costs and benefits specific to your situation.

like image 186
Ash Avatar answered Sep 20 '22 16:09

Ash