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

Recommended Answers

All 2 Replies

Pass by const reference if you want to accept literals:

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.