Hi,

I have a question about constructors and the difference between passing by value and by reference.

If you look at the two examples I attached. Example one has a constructor that passes by value and example two pass by reference. Now I want to know why example one will use the constructor:

myc():itsvalue(0) {}

to convert this line

myc m(123, 456);

and work but example two will fail to compile saying no valid constructor found..Why does this happen?

Example-One

#include <iostream>

class myc
{
  
public:
  
  typedef unsigned long size_type;
  
  myc():itsvalue(0) {}
  myc(size_type val):itsvalue(val) {}
  myc(myc a, myc b):itsvalue(a.itsvalue + b.itsvalue) {}//This is the constructor by value
  
  friend std::ostream& operator<<(std::ostream & out, const myc & c);
  
private:
  
  size_type itsvalue;
  
};

std::ostream& operator<<(std::ostream & out, const myc & c)
{
  return out << c.itsvalue;
}

int main()
{
  myc m(123, 456);//converts literal integers with myc(size_type val):itsvalue(val) {}
  
  std::cout << m << std::endl;
  return 0;
}

Example-Two

#include <iostream>

class myc
{
  
public:
  
  typedef unsigned long size_type;
  
  myc():itsvalue(0) {}
  myc(size_type val):itsvalue(val) {}
  myc(myc & a, myc & b):itsvalue(a.itsvalue + b.itsvalue) {}//This is the constructor by reference
  
  friend std::ostream& operator<<(std::ostream & out, const myc & c);
  
private:
  
  size_type itsvalue;
  
};

std::ostream& operator<<(std::ostream & out, const myc & c)
{
  return out << c.itsvalue;
}

int main()
{
  myc m(123, 456);//Now myc(size_type val):itsvalue(val) {} fails to convert the literal inetegers
  
  std::cout << m << std::endl;
  return 0;
}

Edited 6 Years Ago by gerard4143: n/a

Pass by const reference if you want to accept literals:

myc(myc const& a, myc const& b):itsvalue(a.itsvalue + b.itsvalue) {}
Comments
Thanks for the rookie tip

Pass by const reference if you want to accept literals:

myc(myc const& a, myc const& b):itsvalue(a.itsvalue + b.itsvalue) {}

Yes of course, how do we expect to change a literal..Its funny how simple the answer is when someone else points it out.

This question has already been answered. Start a new discussion instead.