473,324 Members | 2,581 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,324 software developers and data experts.

Constructor denial?

Is it possible to have a constructor REFUSE to be constructed? That is, can
one within a constructor check to see if I really want to be constructed,
and return a nullptr instead of a valid object address when a construction
is attempted? Note that 'in the old days', a call to malloc( ) would return
'null' if it couldn't make the allocation for some reason. I'm wondering if
this capability has been preserved in 'gcnew'?

Immediately I can see why this wouldn't be possible if you allow stack
semantics. But I also have noticed that I can't create arrays in stack
semantics (the elements can be objects, but the array must be instantiated
as a pointer). Thus, such restrictions, not allowing stack semantics for
some cases, is not without its precedence...

Not really anything to do with my projects, just a thought that came to
mind...

[==P==]
Jan 3 '06 #1
10 1139
there are 2 things you can do:
- throw an exception, but then you'll have to catch it.
- create a custom 'new' operator that returns NULL if it determines that
your constructor failed. you'd have to make some mechanism to let your new
operator know that the constructor failed, but that would work i think.

kind regards,
Bruno.
"Peter Oliphant" <po*******@RoundTripInc.com> wrote in message
news:Ov**************@tk2msftngp13.phx.gbl...
Is it possible to have a constructor REFUSE to be constructed? That is,
can one within a constructor check to see if I really want to be
constructed, and return a nullptr instead of a valid object address when a
construction is attempted? Note that 'in the old days', a call to
malloc( ) would return 'null' if it couldn't make the allocation for some
reason. I'm wondering if this capability has been preserved in 'gcnew'?

Immediately I can see why this wouldn't be possible if you allow stack
semantics. But I also have noticed that I can't create arrays in stack
semantics (the elements can be objects, but the array must be instantiated
as a pointer). Thus, such restrictions, not allowing stack semantics for
some cases, is not without its precedence...

Not really anything to do with my projects, just a thought that came to
mind...

[==P==]

Jan 3 '06 #2
Peter Oliphant wrote:
Is it possible to have a constructor REFUSE to be constructed?


Yes, this is why exceptions were invented.
B.
Jan 3 '06 #3
Yes, I can see how exception processing could be used, but this requires
putting all construction attempts of the class in a try/catch block (at some
level).

Therefore this isn't a 'solution' to what I asked about. That is, having a
constructor just return 'nullptr' to deny construction. Note that 'malloc'
returns a 'null' and requires no exception processing *on the part of the
caller*.

Now, one way is to wrap the constructor in another class that attempts the
construction and returns a nullptr if the exception fires, or a pointer to
the newly constructed instance of original class if successful (a 'factory',
if you will). And such a method could be made static. That would work, but
is cumbersome.

I'm guessing it's not possible to actually just return 'nullptr' in a
construction attempt like 'malloc' does...

[==P==]

"Bronek Kozicki" <br**@rubikon.pl> wrote in message
news:af***************************@news.news-service.com...
Peter Oliphant wrote:
Is it possible to have a constructor REFUSE to be constructed?


Yes, this is why exceptions were invented.
B.

Jan 4 '06 #4
Peter Oliphant wrote:
I'm guessing it's not possible to actually just return 'nullptr' in a
construction attempt like 'malloc' does...


You can add a static member to the class, and call that instead of the
constructor. It doesn't require a separate factory class. You can
optionally make the constructor private, if you want to force your own
function instead.

class C
{
public:
C();
static C* TryCreate()
{
try
{
C* c = new C;
return c;
}
catch(...)
{
return 0;
}
}
};

You can apply the same idea to C++/CLI. It's not that cumbersome, but I
don't see why you prefer nullptr to an exception. If construction fails,
that's almost always an error, and therefore the exception is valid.

Optionally, you can set a failed flag in the constructor, and add a bool
IsValid() const member function. It's very good for classes that can
fail for a valid reason, which as a FileStream.

Tom
Jan 4 '06 #5
Peter Oliphant wrote:
Yes, I can see how exception processing could be used, but this requires
putting all construction attempts of the class in a try/catch block (at some
level).


yes, but trick with using exceptions *correctly* is to have very few of
these try/catch blocks. Thus you won't use such a block to handle single
failed construction; instead you will put it where it does make most
sense to present all errors to the user or otherwise *sensible* recover
from error condition (without gimmics to pretend that everything is
under control, when in fact it is not, in this particular part of code).
I encourage you to read Herb Sutter's "Exceptional C++" series of books
to understand more of this. These books are pretty good read, actually
(especially first and third one, at least to me)
B.
Jan 4 '06 #6
Or you can supply your own 'new' operator for that class. in that case you
can use a flag or an exception in your constructor to signal that
construction has failed, and let the 'new' operator return a NULL pointer.

kind regards,
Bruno.
"Tamas Demjen" <td*****@yahoo.com> wrote in message
news:%2***************@TK2MSFTNGP10.phx.gbl...
Peter Oliphant wrote:
I'm guessing it's not possible to actually just return 'nullptr' in a
construction attempt like 'malloc' does...


You can add a static member to the class, and call that instead of the
constructor. It doesn't require a separate factory class. You can
optionally make the constructor private, if you want to force your own
function instead.

class C
{
public:
C();
static C* TryCreate()
{
try
{
C* c = new C;
return c;
}
catch(...)
{
return 0;
}
}
};

You can apply the same idea to C++/CLI. It's not that cumbersome, but I
don't see why you prefer nullptr to an exception. If construction fails,
that's almost always an error, and therefore the exception is valid.

Optionally, you can set a failed flag in the constructor, and add a bool
IsValid() const member function. It's very good for classes that can fail
for a valid reason, which as a FileStream.

Tom

Jan 4 '06 #7
Bruno van Dooren wrote:
Or you can supply your own 'new' operator for that class. in that case you
can use a flag or an exception in your constructor to signal that
construction has failed, and let the 'new' operator return a NULL pointer.


nothrow variant of new operator must not return null, while throw
variant must be explicitly called and always checked for null, which is
at least cumbersome. Futhermore, operator new does not have access to
constructor parameters.

If you want object construction to fail, just throw an exception during
construction. If you do not want exceptions (eg. due to performance
reasons), use factory or static function and create object on heap,
allowing null pointer to be returned when object cannot be created - but
be aware that heap allocations are much more expensive than creating
object on stack. See also http://www.gotw.ca/gotw/066.htm
B.
Jan 4 '06 #8
Peter Oliphant wrote:
Yes, I can see how exception processing could be used, but this
requires putting all construction attempts of the class in a
try/catch block (at some level).

Therefore this isn't a 'solution' to what I asked about. That is,
having a constructor just return 'nullptr' to deny construction. Note
that 'malloc' returns a 'null' and requires no exception processing
*on the part of the caller*.


Returning a "nullptr" requires the caller to check for luillity (because
dereferencing a nll pointer is invalid of course). So whatever method you
use (exception or anything else), if a constuctor can "fail", the caller
that want to construct an object *must* check wether the creation failed or
not. Only the syntaxic form of the check changes, not it's necessity.

Btw, if used correctly, exceptions allow to have only a few error checks
(catch clauses), at least less than the "if"s necessary to check errors in
C.

Arnaud
MVP - VC
Jan 4 '06 #9
Bronek Kozicki wrote:
Bruno van Dooren wrote:
Or you can supply your own 'new' operator for that class. in that case
you can use a flag or an exception in your constructor to signal that
construction has failed, and let the 'new' operator return a NULL
pointer.

nothrow variant of new operator must not return null, while throw
variant must be explicitly called and always checked for null, which is
at least cumbersome. Futhermore, operator new does not have access to
constructor parameters.


I think you have that the wrong way. The new variant that does not
throw MAY return a NULL pointer to indicate failure, whereas the new
that throws must not, instead resulting in an exception being thrown.

-n
Jan 5 '06 #10
Nikolaos D. Bougalis wrote:
I think you have that the wrong way. The new variant that does not
throw MAY return a NULL pointer to indicate failure, whereas the new
that throws must not, instead resulting in an exception being thrown.


this is what I meant; sorry for confussion.
B.
Jan 5 '06 #11

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

Similar topics

3
by: Jun | last post by:
I have following script <script> var Animal = function(name){ this.name = name; } Animal.prototype.eat = function (food) {
15
by: A | last post by:
Hi, A default copy constructor is created for you when you don't specify one yourself. In such case, the default copy constructor will simply do a bitwise copy for primitives (including...
18
by: Matt | last post by:
I try to compare the default constructor in Java and C++. In C++, a default constructor has one of the two meansings 1) a constructor has ZERO parameter Student() { //etc... } 2) a...
9
by: Player | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all. I am in the process of teaching myself C# and I think I am doing OK. I have learnt how to how to call the right constructor of a...
45
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using...
8
by: shuisheng | last post by:
Dear All, I am wondering how the default copy constructor of a derived class looks like. Does it look like class B : public A { B(const B& right) : A(right) {}
74
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the...
13
by: sam_cit | last post by:
Hi Everyone, I have the following unit to explain the problem that i have, class sample { public : sample() { printf("in sample...\n"); }
4
by: sakthikumarb | last post by:
Hi, There is any wmi event for deniel of service attack.if not,there is any other procedure to get a event for Denial of Service attack . Thanks in advance, Regards, Sakthi
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...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.