473,323 Members | 1,570 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

returning value from constructors

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.
What if I want to check whether the object is successfully created. We
could have checked that by returning some value and finding it.

Oct 29 '06 #1
6 2786
Kavya wrote:
What if I want to check whether the object is successfully created. We
could have checked that by returning some value and finding it.
That's what you use exceptions for.

- J.
Oct 29 '06 #2
* 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?
Oct 29 '06 #3
Kavya:
What if I want to check whether the object is successfully created. We
could have checked that by returning some value and finding it.
Two Strategies:

(1) If construction fails, throw an exception.

class MyClass {
public:

MyClass(int const i)
{
if (42==i) throw -1;
}
};

(2) Check the state after construction:

MyClass obj;

if ( !obj.IsOpen() ) return -1;

--

Frederick Gotham
Oct 29 '06 #4
"Kavya" <Le******@gmail.comwrote:
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.
What if I want to check whether the object is successfully created. We
could have checked that by returning some value and finding it.
If a constructor returned a bool (true for success and false for failure
to create say,) then what would the following line of code mean?

MyClass myObject;

After the line, does 'myObject' exist or not?

--
To send me email, put "sheltie" in the subject.
Oct 29 '06 #5
"Kavya" <Le******@gmail.comwrote in message
news:11**********************@f16g2000cwb.googlegr oups.com...
>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.
What if I want to check whether the object is successfully created. We
could have checked that by returning some value and finding it.
Okay, say you have a constructor that returns some val. So what does this
do?

MyClass MyInstance; // default constructor
MyClass = MyClass( 10 );

A constructor can be thought of as returning a value, the class itself.
Anythign else and how could you do code like that?
Oct 29 '06 #6
Jim Langston wrote:
[..]
A constructor can be thought of as returning a value, the class
itself. [..]
I think it's better to say that it returns *an instance* of the
class rather than "the class".

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 29 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: mjm | last post by:
Folks, Stroustrup indicates that returning by value can be faster than returning by reference but gives no details as to the size of the returned object up to which this holds. My question is...
6
by: JKop | last post by:
unsigned int CheesePlain(void) { unsigned int const chalk = 42; return chalk; } unsigned int& CheeseRef(void) {
12
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline...
4
by: Siemel Naran | last post by:
Hi. I have found one advantage of returning values through the argument list. It's that we have to store the return value. But when we return by value, we may forgot to store the return value. ...
1
by: Matthias De Ridder | last post by:
Hello, I really hope that someone will be able to help me, because I'm desperate now! I'm a student, graduating this year, and I'm working on a thesis where C# Web Services are involved. I...
9
by: Peter Oliphant | last post by:
I've been told that value structs can have default constructors (I'm using VS C++.NET 2005 PRO using clr:/pure syntax). But the following code generates the following error: value struct...
12
by: Edward Diener | last post by:
Given value class X { public: // Not allowed: X():i(100000),s(10000) { } // Allowed void InitializeDefaults() { i = 100000; s = 10000; } private: int i;
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
9
by: Hank Stalica | last post by:
So I've made a linked list class. I have a function that initiates this class, opens a file, parses it, and then inserts nodes into this temporary class. What I would like to do is then have...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.