c++-cli

How can I prevent collision of functions of similar name? One of the functions is used instead and the other is ignored


When two functions of similar name are defined, one of them seems to be silently discarded and the other one used instead. (It's not predictable which of the functions will be discarded.)

I've replicated the problem in the code below, where class C has member functions C::X() and static C::X(C*)

It seems to be a name collision bug in the compiler. Can the C++/CLI compiler be instructed to detect when such a name collision occurs?

(Using Visual Studio 2022)

// Main.cpp
// Compile with /clr (common language runtime support)

#include <iostream>
class C
{
public:
  void P() {
    std::cout << "c.P()" << std::endl;
  }
  static void X(C* c) {
    std::cout << "C::X(C*)" << std::endl;
    c->X(); // bug - infinitely re-entrant call, going to the wrong function
  }
  void X() {
    std::cout << "c.X()" << std::endl;
    P(); // bug - this should be called instead
  }
};

int main() {
  C c;
  C::X(&c);
  c.X();
  return 0;
}

// Expected call behaviour: C::X(&c) -> c.x() -> c.p()
//  C::X(C*)
//  c.X()
//  c.P()
// Instead, there is a collision of function names so one of two bugs occurs
// Bug 1: calls c.X() instead of C::X(C*), causing unexpected message
//  c.X()
//  c.P()
// Bug 2: calls C::X(C*) instead of c.X(), causing infinite recursion
//  C::X(C*)
//  C::X(C*)
//  ...
// Debugger shows incorrect position, look at output to see what's actually executed

Solution

  • The problem can cause function calls to be misdirected, and has lead to many wasted hours debugging the wrong issue.

    This sample code reproduced the problem in 17.13.0 but not in 17.14.2.

    The problem is resolved by updating Visual Studio 2022 to the latest version.