473,394 Members | 1,739 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,394 software developers and data experts.

NULL

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
12 1713
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
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
* 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
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
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
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
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
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
"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
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
"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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: Agoston Bejo | last post by:
I want to enforce such a constraint on a column that would ensure that the values be all unique, but this wouldn't apply to NULL values. (I.e. there may be more than one NULL value in the column.)...
3
by: iStrain | last post by:
Hiya. I'm _sure_ this is an FAQ, but Googling hasn't produced the answer in a way I can make sense out of. I know I should get this, but so far no way... I'm creating tables and doing queries in...
5
by: Mike MacSween | last post by:
This as the row source for a combo: SELECT qryRole.RoleID, qryRole.Role FROM qryRole WHERE (((qryRole.RoleID) Not In (SELECT RoleID FROM qryRoleEvent INNER JOIN qryEvent ON qryRoleEvent.EventID...
3
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
102
by: junky_fellow | last post by:
Can 0x0 be a valid virtual address in the address space of an application ? If it is valid, then the location pointed by a NULL pointer is also valid and application should not receive "SIGSEGV"...
29
by: Jason Curl | last post by:
I've been reading this newsgroup for some time and now I am thoroughly confused over what NULL means. I've read a NULL pointer is zero (or zero typecast as a void pointer), others say it's...
5
by: David Sworder | last post by:
Hi, I've created a UserControl-derived class called MyUserControl that is able to persist and subsequently reload its state. It exposes two methods as follows: public void Serialize(Stream...
64
by: yossi.kreinin | last post by:
Hi! There is a system where 0x0 is a valid address, but 0xffffffff isn't. How can null pointers be treated by a compiler (besides the typical "solution" of still using 0x0 for "null")? -...
0
by: Aaron Morton | last post by:
I'm working on a IHttpModule that handles the PreSendRequestHeaders event from the HttpApplication, if the event is raised after EndRequest then HttpContext.Current is null. If it is raised before...
46
by: lovecreatesbea... | last post by:
Do you prefer malloc or calloc? p = malloc(size); Which of the following two is right to get same storage same as the above call? p = calloc(1, size); p = calloc(size, 1);
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.