开发者

calling priority of polymorphism function with char* argument and bool argument in C++

开发者 https://www.devze.com 2023-01-23 17:00 出处:网络
The following is the code snippet. #include <stdio.h> void bar(char* ptr) { printf(\"开发者_StackOverflow社区bar(char*) is called\\n\");

The following is the code snippet.

#include <stdio.h>

void bar(char* ptr) {
  printf("开发者_StackOverflow社区bar(char*) is called\n");
}

void bar(bool ptr) {
  printf("bar(bool) is called\n");
}

int main() {
  const char* str = "abc";
  bar(str);

  return 0;
}

When bar() is passed a const char* parameter, why bar(bool) is called? Shouldn't bar(char*) be called?


The reason is that there is no implicit conversion from const char* to char* but there is one from const char* to bool.

Here is an example when bar(const char*) is called (note added const):

#include <stdio.h>

void bar(const char* ptr) { printf("bar(const char*) is called\n"); }
void bar(bool ptr) { printf("bar(bool) is called\n"); }

int main()
{
    const char* str = "abc";
    bar(str);
    return 0;
}


This is correct behavior by the compiler. bar(char*) cannot be called with a const char * argument, as that would defeat const-correctness. On the other hand, bar(bool) is a valid choice, so that is what gets called. If you had bar(const char*) instead of bar(char*), then bar(const char*) would of course been preferred over bar(bool) for the call bar(str).

0

精彩评论

暂无评论...
验证码 换一张
取 消