2

I felt confused for c++ overloaded functions mathing. see code below:

#include <iostream>

using namespace std;

class Base {
public:
  void func();
  void func(int);
};

void Base::func() { cout << "Base::func()" << endl; }

void Base::func(int a) { cout << "Base::func(int)" << endl; }

class Derived : public Base {

public:
  void func(const string &);
  void func(const string &&);
  void func(bool);
};

void Derived::func(const string &s) {
  cout << "Derived::func(string &)" << endl;
}

void Derived::func(const string &&s) {
  cout << "Derived::func(string &&)" << endl;
}

void Derived::func(bool b) { cout << "Derived::func(bool)" << endl; }

int main() {

  Derived d;
  d.func("biancheng");
  d.func(false);

  // d.func(1);
  // d.Base::func(1);

  cout << endl << "completed .." << endl;
  return 0;
}

and the results:

Derived::func(bool)
Derived::func(bool)

completed ..

For calling d.func("biancheng");, the result printed matched the func(bool) function definition. Can somebody help me understand what is the cause?

I thought it would be one of the func(const string &s) or func(const string &&s).

sanren1024
  • 37
  • 5
  • I wondered why I never stumbled upon this in real code, and I think overloading functions with `std::string` and `bool` parameters really is a bad idea also for other reasons. I think it's fair to say that you should only overload functions if you as the caller _don't care which overload is chosen_. – chrysante Jul 27 '23 at 08:46
  • 1
    Try: `string str = "biancheng";` followed by `d.func(str);` – machine_1 Jul 27 '23 at 08:49

2 Answers2

3

"biancheng" is of type char const[10]. It decays to char const*. From here there are two possible conversions. There is the implicit (built in) conversion to bool and the implicit conversion to the class type std::basic_string<char, /*char-traits-type and allocator*/>. Conversions to class types are always considered after built in conversions, so the pointer to bool conversion is chosen here by the compiler.

chrysante
  • 2,328
  • 4
  • 24
-1

In your code, when you called function d.func("biancheng");, it matched with d.func(bool b) because the string parameter "biancheng" can be implicitly converted to TRUE [boolean parameter]. Therefore, d.func(bool b) was called instead of d.func(const string &s) || d.func(const string &&s).

Vraj Bhatt
  • 174
  • 7