Vladislav Kolontai
Vladislav Kolontai

Reputation: 169

Class method and argument passing

I have been programming and I have spotted strange behavior in c++ classes. So I made simple class that contains string, constructor for that class and friend method(show) that prints string from object. But as you can see in main function. I pass to method(show) simple string and it works. I found it convenient, but why it worked if method parameter is reference to an object?

#include <iostream>
using namespace std;

class lol
{
  char * str;
public:
  lol(const char * s);
  friend void show(const lol & l);
};

lol::lol(const char * s)        //assign string to object
{
  str = new char[strlen(s)+1];
  strcpy(str,s);
}

void show(const lol & l)        //prints string from object
{   
  cout << l.str;
};

int main()
{
  show("TEST"); //passing string but not an object
  return 0;
};

Upvotes: 3

Views: 127

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126562

I found it convenient, but why it worked if method parameter is reference to an object?

It works because your lol class defines a constructor accepting a const char* and which is not marked as explicit.

This authorizes the compiler to resolve the call show("TEST") by constructing a temporary object of type lol, passing the string literal "TEST" as the argument to the constructor, and binding your reference argument l to this temporary object.

To prevent implicit user-defined conversion sequences of this kind, mark your constructor as explicit:

class lol
{
    char * str;
public:
    explicit lol(const char * s);
//  ^^^^^^^^
    friend void show(const lol & l);
};

This way, the call show("TEST") will result in a compiler error.

Upvotes: 9

Related Questions