-1

I have seen this code

  void path(
    const char * p);
  » more...

void path(
    const std::string & p);
  » more...

Can I do the following modification, basically reversing the * and &.

void path(
    const char & p);
  » more...

void path(
    const std::string * p);
  » more...
lilzz
  • 5,243
  • 14
  • 59
  • 87

3 Answers3

3

The first is passing an array of characters as a pointer to the first one. This is how strings are conventionally handled in C, and you sometimes see it in C++ due to the common heritage of the two languages. While you could pass a reference and carefully document that it's actually supposed to be an array, it would be confusing to anyone used to that convention.

The second is passing a single object by reference. While you could emulate the reference with a pointer, this would be (mildly) confusing to anyone used to the reference semantics of C++.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

You should understand what the function is trying to do before changing.

Lets see what happens when you change void path(const char * p); to void path(const char &p);

Probably the reason a char * is passed could be that the function needs to access an array of characters. And if you change the parameter to char &p, then the function only accepts a char by reference.

Varun
  • 691
  • 4
  • 9
-1

yes you can. but you must be careful with the use of . and -> in these function

and keep in mind that the meaning compelitly changes

Hossein Nasr
  • 1,436
  • 2
  • 20
  • 40