Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What patterns do you use to decouple interfaces and implementation in C++?

One problem in large C++ projects can be build times. There is some class high up in your dependency tree which you would need to work on, but usually you avoid doing so because every build takes a very long time. You don't necessarily want to change its public interface, but maybe you want to change its private members (add a cache-variable, extract a private method, ...). The problem you are facing is that in C++, even private members are declared in the public header file, so your build system needs to recompile everything.

What do you do in this situation?

I have sketched two solutions which I know of, but they both have their downsides, and maybe there is a better one I have not yet thought of.

like image 946
Tobias Avatar asked Jun 09 '09 23:06

Tobias


People also ask

How do you decouple a code?

Decoupling is a coding strategy that involves taking the key parts of your classes' functionality (specifically the hard-to-test parts) and replacing them with calls to an interface reference of your own design. With decoupling, you can instantiate two classes that implement that interface.

What is decoupled architecture c#?

Decoupled architecture is an architectural approach that allows each computing component to exist and perform tasks independently of one another, while also allowing the components to remain completely unaware and autonomous until instructed.


2 Answers

Using inheritance:

In your header, declare the public methods as pure virtual methods and a factory.

In your source, derive an implementation class from your interface and implement it. In the implementation of the factory return an instance of the implementation.

Plus:

  • Allows you to change the implementation of your class without having to recompile everything.
  • Easy and foolproof to implement.

Minus:

  • Really awkward to define a (public) derived instance of the public base class which should inherit some of the methods of the (private) implementation of the public base.
like image 167
Tobias Avatar answered Oct 25 '22 04:10

Tobias


John Lakos' Large Scale C++ Software Design is an excellent book that addresses the challenges involved in building large C++ projects. The problems and solutions are all grounded in reality, and certainly the above problem is discussed at length. Highly recommended.

like image 26
Greg Hewgill Avatar answered Oct 25 '22 02:10

Greg Hewgill