DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Why constructors don't have return types (http://www.daniweb.com/forums/thread31203.html)

SpS Aug 26th, 2005 6:19 am
Why constructors don't have return types
 
Can anyone explain me in simple language and better if with an example why constructor don't have return types :!:

Ancient Dragon Aug 26th, 2005 9:03 am
Re: Why constructors don't have return types
 
Probably because the are not explicitely called in your code, so what good would it do to return a value -- nobody is going to be listening.

The constructor is only called when you instantiate an object. There is no way to catch the return value of the constructor.
// This doesn't make sense!!
int x = CMyClass SomeObject;

Narue Aug 26th, 2005 9:08 am
Re: Why constructors don't have return types
 
>Can anyone explain me in simple language and better if with an
>example why constructor don't have return types
Here's an idea. Show us how it could be done without breaking all kinds of existing code, and you'll answer your own question.

SpS Aug 26th, 2005 9:33 am
Re: Why constructors don't have return types
 
Thanx alot i guess it actually doesn't make any sense

I was searching net and came across one answer and it said having return types of constructor means taking address of constructor(which is illegal)...can u explain me this....

sorry for asking such queries (i am bit new to C++)

Ancient Dragon Aug 26th, 2005 1:57 pm
Re: Why constructors don't have return types
 
Quote:

Originally Posted by sunnypalsingh
...can u explain me this....

Nope. I don't know what taking the address of a function has to do with returning a value. constructors don't return values because c++ standards and language say they don't. ;)

Dante Shamest Aug 27th, 2005 3:18 pm
Re: Why constructors don't have return types
 
How can I handle a constructor that fails?

Ancient Dragon Aug 27th, 2005 3:59 pm
Re: Why constructors don't have return types
 
Another option -- don't put any code in the constructor that might cause it to fail. M$ MFC is good at that -- first instantiate the object and then call its Create() method. The constructor only initializes class data to some default value (normally 0). Then the Create() method initializes all the rest and either returns a value or throws and exception.

Dante Shamest Aug 27th, 2005 4:22 pm
Re: Why constructors don't have return types
 
Yes, one could use MFC's 2-stage construction. However, my personal preference is still to to use the constructor to create the object, because I'm used to the RAII paradigm, and my own wrappers for the Windows API use it.


All times are GMT -4. The time now is 8:18 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC