How can I make the class `Engine` "private"? That is, for any user of the library, the class `Engine` shoule not be visible. The user should only have access to `Car`.
Some say that to achieve this, It is needed to put the definition of `Engine` outside the public header. However in my case the class `Car` refers to `Engine`, making this not possible.
also didn't quite understand your header problem; can a forward declare resolve it?
finally, the header you give to the user of a compiled library does not have to be the same one you compiled it with, it can be stripped down.
Make Engine part of the implementation. Have Car store a unique_ptr<> to an Engine. That way the user doesn't know anything about the Engine class.
[ Edit: Added ~Car() based on Jens Hirschmann's comment below.]
#include <memory>
// car.h, which you distribute to your customers
class Engine; // forward declaration
class Car {
public:
Car();
void start();
std::unique_ptr<Engine>eng;
~Car();
};
// engine.h, which is part of the implementation, but not distributed
// to customers
class Engine {
public:
void vroom();
};
// car.cpp
// #include "car.h"
// #include "engine.h"
Car::Car() : eng(new Engine) {}
Car::~Car() {} void Car::start() {
eng->vroom();
}
// engine.cpp
// #include "engine.h"
#include <iostream>
void Engine::vroom() { // Note: Car::
std::cout << "vroom\n";
}
int main()
{
Car myCar;
myCar.start();
}