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;
}