Overloaded Constructors: string& vs char* as param

closed account (2AoiNwbp)
Hi guys,

I'm working on the examples from the Reference and need help with one. I added a constructor with a param char* in the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// copy constructor: deep copy
#include <iostream>
#include <string>
using namespace std;

class Example5 {
    string* ptr;
  public:
    Example5 (const string& str) : ptr(new string(str)) {
        cout << "Constructor string&" << endl;}
    Example5 (const char* str) : ptr(new string(str)) {
        cout << "Constructor char*" << endl;}
    ~Example5 () {delete ptr;}
    // copy constructor:
    Example5 (const Example5& x) : ptr(new string(x.content())) {}
    // access content:
    const string& content() const {return *ptr;}
};

int main () {
  Example5 foo ("Example");
  Example5 bar = foo;

  cout << "bar's content: " << bar.content() << '\n';
  cout << "foo's content: " << foo.content() << endl;
  
  system("pause");
  return 0;
}

If I don't add this constructor, the compiler decides that param "Example" in
 
Example5 foo ("Example");

is of type string and works ok. But when I add this other constructor, which I thought it would give me an error, it happens that the compiler decides somehow instead, that it is no longer of type string, but of type char*. So my question is how does the compiler decide to use char* instead of string, and why? is it because char is a fundamental type?
Thanks
Actually the std::string class' constructor has the following prototypes:
http://www.cplusplus.com/reference/string/string/string/

So, while creating a new std::string from char *, it gets stored as a string.
Just change Example5 (const string& str) to Example5 (string& str).
Last edited on
When faced with multiple compatible overloads, the compiler will choose the one that best fits the type of the parameter. By using Example5::Example5(const char *), the compiler is able to avoid creating a temporary std::string.
> how does the compiler decide to use char* instead of string, and why?
> is it because char is a fundamental type?

Yes. Conversion to const char* is a standard conversion; during overload resolution, a standard conversion is preferred over a user-defined conversion (conversion to std::string).
closed account (2AoiNwbp)
Great! so, it's a kind of optimization though, isn't it?
> so, it's a kind of optimization though, isn't it?

No. It has nothing to do with optimization or with temporary objects.

For overload resolution, a standard conversion will be preferred over a user-defined conversion even if the standard conversion happens to be more expensive.
http://coliru.stacked-crooked.com/a/2a05371a8dd3ad1e
closed account (2AoiNwbp)
Ahhh, ok. Thank you very much for the example!
Thank you all bodies!

regards,
Alejandro
Topic archived. No new replies allowed.