By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,510 Members | 1,810 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,510 IT Pros & Developers. It's quick & easy.

NULL

P: n/a
How do you write a function in C++ which returns a class object in
some cases and in others, returns something like a NULL pointer so
that i can know in the callee function that the object doesnt exist??

ClassName A()
{
ClassName a;
if (condition)
return a;
else

Jun 21 '07 #1
Share this Question
Share on Google+
12 Replies


P: n/a
I am sorry i did not intend that...

Here is the complete code...

ClassName A()
{
ClassName a;
if (condition)
return a;
else
return NULL;
}

int main() {
if (A() == NULL)
// Do something
else
// Do something
}

Thanks in advance

On Jun 21, 8:03 pm, Mohitz <coolmoh...@gmail.comwrote:
How do you write a function in C++ which returns a class object in
some cases and in others, returns something like a NULL pointer so
that i can know in the callee function that the object doesnt exist??

ClassName A()
{
ClassName a;
if (condition)
return a;
else

Jun 21 '07 #2

P: n/a
Mohitz wrote:
I am sorry i did not intend that...

Here is the complete code...

ClassName A()
{
ClassName a;
if (condition)
return a;
else
return NULL;
}

int main() {
if (A() == NULL)
// Do something
else
// Do something
}
The classical solution is Barton and Nackman's fallible<>, which I
heartedly recommend having in your personal toolkit. There will be an
implementation in my Breeze C++ library, but it still needs some
polishing. Try googling for more info; it's very easy to implement.
Jun 21 '07 #3

P: n/a
* Gennaro Prota:
The classical solution is Barton and Nackman's fallible<>
Unnecessary, uncalled for and completely redundant syntactic sugar.

A pointer will do *JUST* fine.

--
Martijn van Buul - pi**@dohd.org
Jun 21 '07 #4

P: n/a
Martijn van Buul wrote:
* Gennaro Prota:
>The classical solution is Barton and Nackman's fallible<>

Unnecessary, uncalled for and completely redundant syntactic sugar.

A pointer will do *JUST* fine.
except for the need for deallocation. A smart pointer is definitely
better at this point. Of course, if having dynamic allocation is
acceptable, which is not always the case.

To the OP. If the failure of the condition is exceptional (i.e., in a
normal run of the program it shouldn't happen) consider throwing an
exception.

Regards,

Zeppe
Jun 21 '07 #5

P: n/a
Mohitz wrote:
How do you write a function in C++ which returns a class object in
some cases and in others, returns something like a NULL pointer so
that i can know in the callee function that the object doesnt exist??

ClassName A()
{
ClassName a;
if (condition)
return a;
else
class ClassName {
bool m_valid;
public:
explicit ClassName(bool valid = true) : m_valid(valid) { }
bool IsValid() { return m_valid; }
};

ClassName A() {
ClassName a;
if(condition)
return a;
else
return ClassName(false);
}

Well that lets you test the returned object with IsValid().

If you want to get clever you can define some operators:

operator void*() { return m_valid ? this : 0 ; }
bool operator!() { return !m_valid; }

You can then do
if(A() == NULL)
or
if(!A())
....
Jun 21 '07 #6

P: n/a
On 21 Jun, 13:48, Zeppe <zep_p@.remove.all.this.long.comment.yahoo.it>
wrote:
Martijn van Buul wrote:
* Gennaro Prota:
The classical solution is Barton and Nackman's fallible<>
Unnecessary, uncalled for and completely redundant syntactic sugar.
A pointer will do *JUST* fine.

except for the need for deallocation. A smart pointer is definitely
better at this point. Of course, if having dynamic allocation is
acceptable, which is not always the case.

To the OP. If the failure of the condition is exceptional (i.e., in a
normal run of the program it shouldn't happen) consider throwing an
exception.
both fallible and boost::optional copy the value. exception is
the most natural way if the exceptional case is really exceptional.

IMHO, the simplest way is to simply inline.

if(condition)
{
ClassName a;
use(a);
}
else
handle error
Regards,

Zeppe

DS

Jun 21 '07 #7

P: n/a
On Jun 21, 2:09 pm, Martijn van Buul <p...@dohd.orgwrote:
* Gennaro Prota:
The classical solution is Barton and Nackman's fallible<>
Unnecessary, uncalled for and completely redundant syntactic sugar.
A pointer will do *JUST* fine.
A pointer to what? When it is a question of a fallible
reference, use a pointer. But when you want to return a value,
not a reference, what is the pointer to point to. A local
variable? Definitly not a good idea. Something allocated
dynamically? Requires the user do delete---not a good idea. A
static? Fun and games if the user calls the function a second
time before having finished with the first return value, or in a
multithreaded environment.

Any other ideas?

--
James Kanze (GABI Software, from CAI) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 21 '07 #8

P: n/a
On Jun 21, 3:47 pm, dasjotre <dasjo...@googlemail.comwrote:
On 21 Jun, 13:48, Zeppe <zep_p@.remove.all.this.long.comment.yahoo.it>
wrote:
Martijn van Buul wrote:
* Gennaro Prota:
>The classical solution is Barton and Nackman's fallible<>
Unnecessary, uncalled for and completely redundant syntactic sugar.
A pointer will do *JUST* fine.
except for the need for deallocation. A smart pointer is definitely
better at this point. Of course, if having dynamic allocation is
acceptable, which is not always the case.
A smart pointer is better than what? C++ isn't Java, and if the
object has value semantics, you really don't want pointers to it
all over the place.

The presence of the "elseDefaultTo" function in fallible is also
an advantage; a lot of the time, I can write something like:

int i = c.get().elseDefaultTo( 42 ) ;

and not worry about anything more.
To the OP. If the failure of the condition is exceptional (i.e., in a
normal run of the program it shouldn't happen) consider throwing an
exception.
both fallible and boost::optional copy the value.
Which seems normal? A type with value semantics is meant to be
copied.
exception is
the most natural way if the exceptional case is really exceptional.
And a pointer is the most natural way if the return value should
refer to something that actually exists elsewhere (an entry in a
map, for example).

C++ is a multiparadigm language. There are almost always
several ways to do something, because there is general no one
right way for everything. If you want to return a value, but
it's also to be expected that sometimes you can't, fallible is
the best solution. If you want to return a reference to a
specific object, but it's also expected that sometimes you
can't, a pointer is the best solution. And if you really don't
expect to fail except in exceptional cases, an exception is the
best solution. And there are doubtlessly situations where other
solutions are appropriate (such as passing in a default value
which will be returned in case of error, or designing a null
value for the return type).

--
James Kanze (GABI Software, from CAI) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 21 '07 #9

P: n/a
"Mohitz" <co********@gmail.comwrote in message
news:11*********************@i38g2000prf.googlegro ups.com...
How do you write a function in C++ which returns a class object in
some cases and in others, returns something like a NULL pointer so
that i can know in the callee function that the object doesnt exist??

ClassName A()
{
ClassName a;
if (condition)
return a;
else
Returning a pointer (as others have commented on) is a valid method. The
method I use for this, however, is to throw, since I want to return a
reference.

CPlayer& FindPlayer( const std::string Name )
{
for ( map_player::iterator i = World.ConnectedPlayers.begin(); i !=
World.ConnectedPlayers.end(); ++i)
{
if ( (*i).second.Character.Name == Name )
return (*i).second;
}

throw 0;

}

//////////////////

try
{
CPlayer& TargetPlayer = FindPlayer( Name );
PlayerMoveTo( TargetPlayer, ThisPlayer.Character.Map,
ThisPlayer.Character.Pos );
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + "
summoned." );
}
catch ( int )
{
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + " not
found." );
}

Jun 23 '07 #10

P: n/a
On Jun 23, 1:19 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
Returning a pointer (as others have commented on) is a valid method. The
method I use for this, however, is to throw, since I want to return a
reference.

CPlayer& FindPlayer( const std::string Name )
{
for ( map_player::iterator i = World.ConnectedPlayers.begin(); i !=
World.ConnectedPlayers.end(); ++i)
{
if ( (*i).second.Character.Name == Name )
return (*i).second;
}

throw 0;

}

//////////////////

try
{
CPlayer& TargetPlayer = FindPlayer( Name );
PlayerMoveTo( TargetPlayer, ThisPlayer.Character.Map,
ThisPlayer.Character.Pos );
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + "
summoned." );
}
catch ( int )
{
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + " not
found." );
}
next time, don't be so cheap and use an exception class instead of an
ordinary int (which does not hold any error info)

Diego

Jun 25 '07 #11

P: n/a
"Diego Martins" <jo********@gmail.comwrote in message
news:11**********************@o61g2000hsh.googlegr oups.com...
On Jun 23, 1:19 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
>Returning a pointer (as others have commented on) is a valid method. The
method I use for this, however, is to throw, since I want to return a
reference.

CPlayer& FindPlayer( const std::string Name )
{
for ( map_player::iterator i = World.ConnectedPlayers.begin(); i !=
World.ConnectedPlayers.end(); ++i)
{
if ( (*i).second.Character.Name == Name )
return (*i).second;
}

throw 0;

}

//////////////////

try
{
CPlayer& TargetPlayer = FindPlayer( Name );
PlayerMoveTo( TargetPlayer, ThisPlayer.Character.Map,
ThisPlayer.Character.Pos );
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + "
summoned." );
}
catch ( int )
{
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + " not
found." );
}

next time, don't be so cheap and use an exception class instead of an
ordinary int (which does not hold any error info)
It doesn't need to hold any error info. If it throws, I know the error was
the key was not found, since that's all the function does. So why should I
bother setting up an exception class for an exception I will never look at?
Jun 26 '07 #12

P: n/a
On Jun 26, 1:21 am, "Jim Langston" <tazmas...@rocketmail.comwrote:
"Diego Martins" <jose.di...@gmail.comwrote in message

news:11**********************@o61g2000hsh.googlegr oups.com...
On Jun 23, 1:19 pm, "Jim Langston" <tazmas...@rocketmail.comwrote:
Returning a pointer (as others have commented on) is a valid method. The
method I use for this, however, is to throw, since I want to return a
reference.
CPlayer& FindPlayer( const std::string Name )
{
for ( map_player::iterator i = World.ConnectedPlayers.begin(); i !=
World.ConnectedPlayers.end(); ++i)
{
if ( (*i).second.Character.Name == Name )
return (*i).second;
}
throw 0;
}
//////////////////
try
{
CPlayer& TargetPlayer = FindPlayer( Name );
PlayerMoveTo( TargetPlayer, ThisPlayer.Character.Map,
ThisPlayer.Character.Pos );
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + "
summoned." );
}
catch ( int )
{
SendMessageToPlayer( Socket, MSG_SERVER_MESSAGE, Name + " not
found." );
}
next time, don't be so cheap and use an exception class instead of an
ordinary int (which does not hold any error info)

It doesn't need to hold any error info. If it throws, I know the error was
the key was not found, since that's all the function does. So why should I
bother setting up an exception class for an exception I will never look at?
reusability and mantainability
you could propagate away to another caller

your way seems more like a "goto with stack unwinding"

Jun 26 '07 #13

This discussion thread is closed

Replies have been disabled for this discussion.