e.g.
// Implementation.
struct PrivatePoint {
void SomePrivateMethod();
double x;
double y;
}
struct Point : private PrivatePoint {
double DistanceTo(const Point& other) const;
}
This seems similar to the Pimpl idiom. This has two advantages that I really like:
- SomePrivateMethod is testable. If SomePrivateMethod were instead declared as private in Point, you wouldn't be able to call it from tests. If you declared it as public or protected in Point, tests would be able to call it, but so would regular users of Point.
- Accessing private data is easier to read and write compared to how you'd do it in the Pimpl idiom, because you don't have to go through a pointer e.g.
.
Point::DistanceTo(const Point& other) {
SomePrivateMethod();
double dx = other.x - x;
double dy = other.y - y;
return sqrt(dx * dx + dy * dy);
}
vs.
Point::DistanceTo(const Point& other) {
ptr->SomePrivateMethod();
double dx = other.ptr->x - ptr->x;
double dy = other.ptr->y - ptr->y;
return sqrt(dx * dx + dy * dy);
}