eternalmatt
eternalmatt

Reputation: 3564

How C++ is this code working?

I have a strange bit of code. I must have been hitting my keyboard with my eyes closed because this type of thing is really dumb, but weird thing is, I caught it after the program ran successfully.

struct Number{
private:
  unsigned long longNumber;
public:

   Number(unsigned long n)
   {
      longNumber = n;
   }

  unsigned long getReverse()
  {
      /*some magic that returns an unsigned long */
  }

  inline
  unsigned long getLong()
  {
      return longNumber;  
  }
  inline
  static Number add(Number one, Number two)
  {
      return Number(one.getLong() + two.getLong());
  }
};


int main()
{
  scanf("%lu", n);
  Number number = Number(n);
  number = Number::add(number, number.getReverse());
  return 0;
}

There's more stuff going on in main() of course and Number has few more members and functions, but this is what's important I believe.

If you look in main, you'll see that add() is being passed a Number and an unsigned long, but add() only accepts Number and Number.

What's going on here?

EDIT: added constructor above

Upvotes: 1

Views: 165

Answers (4)

Naveen
Naveen

Reputation: 73493

Since Number has a constructor which accepts unsigned long the compiler is creating a temporary object of type Number from the return value of number.getReverse() and passing it to the add function. If you don't want such implicit conversion to occur, you need to declare the Number constructor as explicit.

Upvotes: 5

Aamir
Aamir

Reputation: 15576

As others said, it is because you don't have an explicit constructor. For more details on why a constructor should be explicit or not, see this SO question

Upvotes: 1

janm
janm

Reputation: 18359

You have left out the constructor that takes a long as an argument.

The second argument to the call: Number::add(number, number.getReverse()) is being converted to a Number temporary.

Upvotes: 1

Guy Sirton
Guy Sirton

Reputation: 8411

You're getting an implicit conversion from long to Number. You're also not showing us all your code or a working segment.

Upvotes: 1

Related Questions