It's very rare that I do any C++ programming these days. However, one of my oldest customers continues to utilize a C++-based optimization/statistics framework that we helped them build many years ago. The project has a wonderful purpose, and we owe quite a bit to some of the first people to trust us (thank you Sommer and Dorry!).
As a Ruby programmer, I've come to love test-driven programming. As such, I've made an effort recently to build a test-based workflow into this existing codebase (not always the easiest thing to do, applying a test-base to a large existing codebase). Today I found myself in dire need of being able to test private functions in C++. As a testament to the poor state of testing in other programming languages, many message boards/threads simply told me that I was testing the wrong thing (you should test the public API, not the private implementation). Well, needless to say, this left me a bit uncomfortable. The fact is, the majority of my code is tucked into private methods, and I'd be left with huge long-running end-to-end tests if I strictly followed this heuristic.
However, I came across one golden nugget, one of the most clever hacks I've seen in some time. By utilizing pre-processor directives, we can temporarily override the meaning of private and protected in C++ code, essentially aliasing it to public.
#define protected public #define private public #include "TheClassHeaderUnderTest.h" #undef protected #undef private
See what this is doing? We wrap the class that we'll be testing in pre-processor directives to interpret protected and private as an alias for public, essentially loading that class (when including the header file) as entirely public. This allows me to access everything! Private methods, private variables, you name it. And now, just like in Ruby, it's no holds barred, allowing me to poke and prod my objects without being wrapped on the wrist by the compiler.
Even better, these directives simply wrap your includes in your test files. In other words, I don't have to change my implementation to achieve this.
A clever hack, no matter the language or technology, is a clever hack. And I absolutely love this hack.
Credit : I discovered this technique as a comment on this wiki.