Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class method and argument passing

Tags:

c++

methods

class

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;
};
like image 594
Vladislav Kolontai Avatar asked Jun 11 '26 10:06

Vladislav Kolontai


1 Answers

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.

like image 154
Andy Prowl Avatar answered Jun 12 '26 22:06

Andy Prowl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!