Why C++ CLI has no default argument on managed types?

Mohsen Sarkar picture Mohsen Sarkar · Mar 16, 2013 · Viewed 13.8k times · Source

The following line has the error Default argument is not allowed.

public ref class SPlayerObj{
private:

    void k(int s = 0){ //ERROR
    }
}

Why C++ has no default argument on managed types ?
I would like to know if there is a way to fix this.

Answer

Hans Passant picture Hans Passant · Mar 17, 2013

It does have optional arguments, they just don't look the same way as the C++ syntax. Optional arguments are a language interop problem. It must be implemented by the language that makes the call, it generates the code that actually uses the default argument. Which is a tricky problem in a language that was designed to make interop easy, like C++/CLI, you of course don't know what language is going to make the call. Or if it even has syntax for optional arguments. The C# language didn't until version 4 for example.

And if the language does support it, how that compiler knows what the default value is. Notable is that VB.NET and C# v4 chose different strategies, VB.NET uses an attribute, C# uses a modopt.

You can use the [DefaultParameterValue] attribute in C++/CLI. But you shouldn't, the outcome is not predictable.