0

In this blog post about dependency injection in C++, the author explain a hybrid approach that uses both templates and interfaces as follows:

ICar.h (publicly visible):

#pragma once

struct ICar
{
    virtual void Drive() = 0;
    virtual ~ICar() = default;
};

std::unique_ptr<ICar> MakeV8Car();
std::unique_ptr<ICar> MakeV6Car();

Car.h (internal):

#pragma once
#include "ICar.h"

template <typename TEngine>
class Car : public ICar
{
public:
    void Drive() override
    {
        m_engine.Start();
        // drive
        m_engine.Stop();
    }

private:
    TEngine m_engine;
};

Car.cpp:

#include "Car.h"
#include "V8Engine.h"
#include "V6Engine.h"

std::unique_ptr<ICar> MakeV8Car()
{
    return std::make_unique<Car<V8Engine>>();
}

std::unique_ptr<ICar> MakeV6Car();
{
    return std::make_unique<Car<V6Engine>>();
}

All of which makes good sense to me, except for the internal part. Let's assume I've created a shared object from the above.

How is Car.h private in the context of this shared object?

I've read on the meaning of a private header in the answer which states:

Keep your data in MyClassPrivate and distribute MyClass.h.

Presumably meaning to not distribute MyClass_p.h, but how does one avoid distributing a header file and still have the .so work?

Sam Hammamy
  • 10,819
  • 10
  • 56
  • 94
  • 1
    It just means that clients of your final `.so` library only ever need to see `ICar.h` to be able to work with your code. So when you distribute your code, just package up the `.so` and `ICar.h`. – quamrana Apr 11 '19 at 15:40
  • I guess I thought by loading the `.so`, then they'll be able to import `Car.h` directly since it's part of the `so`. Now that I think about it,that's why Linux has `-dev` packages, right? – Sam Hammamy Apr 11 '19 at 18:02
  • Not at all. An `.so` (and `.dll`) only contains binary executable code. I presume it would be very difficult to retrieve a usable `.h` file out of them. That's why you have to package up the `.h` files that the client needs. – quamrana Apr 11 '19 at 19:19

0 Answers0