No defaults by default
A colleague recently reminded me of something I've been meaning to write about for years. I don't think you should use default function arguments in C++. If a function does something different, give it a different name. If the operation has sensible defaults, give those defaults a proper home.
They make such a good first impression, too.
void resizeImage(Image& image, int width, bool keepAspectRatio = true);
resizeImage(image, 800);
Most callers want to keep the aspect ratio. The declaration supplies true, so they can leave out the boolean and I only need one function. Fair enough. C++ default argument rules
The call that still compiles
Years ago I worked in a legacy C++ codebase with some very long functions. A function could run to thousands of lines and take ten or more arguments, mostly some combination of int, float, and bool. It had accumulated a lot of callers who needed slightly different things from it.
Take a mesh processing function that can weld vertices by merging ones that are close enough together.
Mesh processMesh(const Mesh& mesh, const Transform& transform,
float weldTolerance = 0.0001f, bool weld = false,
bool recalculateNormals = false, int smoothingPasses = 0);
auto result = processMesh(mesh, transform, 0.001f, true);
Now somebody needs a switch that tells the welder whether to preserve seams. It seems natural to put it next to the other welding settings. They update the caller that needs the new behavior and expect the compiler to point out any other calls they need to fix.
Mesh processMesh(const Mesh& mesh, const Transform& transform,
float weldTolerance = 0.0001f, bool preserveSeams = true,
bool weld = false, bool recalculateNormals = false,
int smoothingPasses = 0);
auto result = processMesh(mesh, transform, 0.001f, true);
The seams are perfectly safe. We've turned the welder off.
Without the trailing defaults, the old call would fail to compile. Here, true lands in preserveSeams, and the default supplies false for weld. The compiler can accept the shifted argument because both parameters are bool. An implicit conversion can do the same thing.
I saw this happen more than once in that codebase, and we often caught it in manual testing. A test that checks whether the vertices were actually welded would catch this one. If you rarely exercise that particular call, the bug can sit there for a while.
Even with a short parameter list
The caller supplies the default argument. Change a literal default from 3 to 5 in a library header and replace the shared library, and an already-built client can keep passing 3. Rebuild another client against the new header and it can pass 5 to the same function. C++ working draft on default arguments
Virtual functions make that division especially odd. The type of the reference decides which default you get, even when both calls run the same implementation. C++ Core Guidelines C.140
struct Smoother {
virtual int smooth(int passes = 3) { return passes; }
};
struct MeshSmoother : Smoother {
int smooth(int passes = 5) override { return passes; }
};
MeshSmoother smoother;
Smoother& base = smoother;
auto a = smoother.smooth(); // MeshSmoother::smooth(5)
auto b = base.smooth(); // MeshSmoother::smooth(3)
One function body, two answers to “what happens if I leave it out?”
What I'd write instead
I'd split up the function. Calling weldVertices is how you ask for welding, so there's no weld flag anymore. The tolerance and seam policy go in WeldOptions, where the seam policy can be an enum. C++ Core Guidelines on strong types and easily swapped arguments
enum class SeamPolicy { preserve, merge };
struct WeldOptions {
float tolerance = 0.0001f;
SeamPolicy seams = SeamPolicy::preserve;
};
Mesh transformMesh(const Mesh& mesh, const Transform& transform);
Mesh recalculateNormals(const Mesh& mesh);
Mesh weldVertices(const Mesh& mesh, WeldOptions options);
Mesh weldVertices(const Mesh& mesh) {
return weldVertices(mesh, WeldOptions{});
}
// If you really need it
Mesh processMesh(const Mesh& mesh, const Transform& transform,
WeldOptions weldOptions) {
auto transformed = transformMesh(mesh, transform);
return weldVertices(transformed, weldOptions);
}
auto transformed = transformMesh(mesh, transform);
auto ordinary = weldVertices(transformed);
auto result = weldVertices(transformed, {.tolerance = 0.001f});
Add another optional member to WeldOptions and .tolerance still means tolerance. That's what I like about C++20 designated initializers. I'd keep processMesh if several callers always transform and weld together. Abseil on option structs
The C++ Core Guidelines prefer default arguments where either approach would work, partly because separate overloads can drift apart. Google's style guide allows stable defaults on non-virtual functions and recommends overloads when in doubt. I'd write the extra overload here. The short weldVertices forwards to the same implementation, so there's only one place that does the welding. C++ Core Guidelines F.51, Google C++ Style Guide on default arguments
Logging is the strongest case I know for keeping the language feature. A default argument of std::source_location::current() captures where you called the logging function. Put the expression inside a forwarding overload and you'll get the location inside the overload. The caller's location is input, though. It's information about this particular call. You can pass it explicitly, and there's no reason to carry that pattern over to something like a welding tolerance. C++ working draft on source location
Splitting the function up takes more work. Next time I review a call, though, weldVertices and .tolerance are right there in the diff. With the old version I have to open the header and count across to the fourth parameter. I might have to open the old header to find out what true meant last Tuesday. Then somebody gets to find and fix the other calls that still compile.
If I hand the change to an AI agent, chances are it'll write the functions and their callers. I'd give it the same instructions I'd give another engineer, including where the project puts defaults and why. I'd run static analysis in CI on everyone's changes. It can flag a new default argument, and I can spend the review deciding whether processMesh is worth having in the first place.
P.S. And while we're at it, use [[nodiscard]]. I'll write about that someday.
Comments