473,804 Members | 3,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1742
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...@gma il.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.c omment.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.orgw rote:
* 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 objektorientier ter Datenverarbeitu ng
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...@googl email.comwrote:
On 21 Jun, 13:48, Zeppe <zep_p@.remove. all.this.long.c omment.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 "elseDefaul tTo" function in fallible is also
an advantage; a lot of the time, I can write something like:

int i = c.get().elseDef aultTo( 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 objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 21 '07 #9
"Mohitz" <co********@gma il.comwrote in message
news:11******** *************@i 38g2000prf.goog legroups.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::ite rator i = World.Connected Players.begin() ; i !=
World.Connected Players.end(); ++i)
{
if ( (*i).second.Cha racter.Name == Name )
return (*i).second;
}

throw 0;

}

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

try
{
CPlayer& TargetPlayer = FindPlayer( Name );
PlayerMoveTo( TargetPlayer, ThisPlayer.Char acter.Map,
ThisPlayer.Char acter.Pos );
SendMessageToPl ayer( Socket, MSG_SERVER_MESS AGE, Name + "
summoned." );
}
catch ( int )
{
SendMessageToPl ayer( Socket, MSG_SERVER_MESS AGE, Name + " not
found." );
}

Jun 23 '07 #10

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

Similar topics

26
45458
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.) How can I achieve this? I suppose I would get the most-hated "table/view is changing, trigger/function may not see it" error if I tried to write a trigger that checks the uniqueness of non-null values upon insert/update.
3
2133
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 Perl, and Nulls have started to bother me greatly. The first issue is, as far as I understand it, a column should be NOT NULL if it is necessary (required) data. Now, if a column doesn't have to be NOT NULL; that is, it's not _required_ data,...
5
4258
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 = qryEvent.EventID WHERE ProdID = Forms!frmProductions!ProdID))) ORDER BY qryRole.Role; If there is just one RoleID with a null value in the subquery then the main
3
7663
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
102
6077
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" ( i am talking of unix machine ) while trying to read that location. Then how can i distinguish between a NULL pointer and an invalid location ? Is this essential that NULL pointer should not point to any of the location in the virtual address...
29
3772
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 compiler dependent (and that NULL might be anything, but it is always NULL). The source snippet is below. The question is: - When I use calloc to allocate a block of memory, preinitialising it to zero, is this equivalent (and portable C) to...
5
24733
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 s); public void Deserialize(Stream s); Within the MyUserControl class, there is a field of type MyInnerClass
64
3961
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")? - AFAIK C allows "null pointers" to be represented differently then "all bits 0". Is this correct? - AFAIK I can't `#define NULL 0x10000' since `void* p=0;' should work just like `void* p=NULL'. Is this correct?
0
5409
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 EndRequest (by turning response buffering off) then HttpContext.Current is set. To repo add the following to Global.asax protected void Application_PreSendRequestHeaders(object sender, EventArgs e) {...
46
3699
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
9591
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10594
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10331
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10087
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9166
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7631
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5529
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.