* Kavya:
I was reading a book Test Your C++ Skills by Yashwant Kanetkar. There
was a question in it
Ques: Why constructors do not have return values?
Ans :Constructors are called whenever an object is created. And there
can never exist a situation where we want to return a value at the time
of creation of an object.
I don't understand why author says that.
Most probably because of a lack of imagination & experience.
What if I want to check whether the object is successfully created. We
could have checked that by returning some value and finding it.
Yes, but C++ is designed -- intentionally and/or perhaps just as a
consequence of Doing The Right Thing -- for using exceptions for this.
When a constructor fails, let it throw an exception. That way there
will never be any uninitialized, unusable objects around.
If you will, read the last sentence again.
The real reason why C++ constructors don't have return values, other
than the object created, is that that would force a much less convenient
and much less safe, not to mention much less efficient, syntax for
calling constructors. Consider:
std::cout << std::string( 40, ' ' ) << std::endl;
What if this std::string constructor returned a bool, say? Instead of
the single line above you'd have to do something like
{
std::string spaces; // Not initialized in this hypothetical C++.
if( !create( spaces, 40, ' ' ) )
{
std::runtime_error ex;
if( !create( ex, "Bah!" ) ) { std::terminate(); }
throw ex;
}
else
{
try
{
std::cout << spaces << std::endl;
destroy( spaces );
}
catch( std::exception& )
{
destroy( spaces );
throw;
}
}
}
Argh!
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?