Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 394
Mohsen Sarkar Avatar asked Mar 16 '13 20:03

Mohsen Sarkar


2 Answers

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.

like image 133
Hans Passant Avatar answered Oct 10 '22 09:10

Hans Passant


In addition to the precise answer from Hans Passant, the answer to the second part on how to fix this, you are able to use multiple methods with the same name to simulate the default argument case.

public ref class SPlayerObj {
  private:
    void k(int s){ // Do something useful...
    }
    void k() { // Call the other with a default value 
       k(0);
    }
}
like image 45
holroy Avatar answered Oct 10 '22 09:10

holroy