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

question about objects passed into constructors

Hello,

I have a question about passing an object into a constructor.

How can I check to make sure that the object is good/valid that is
being passed into the constructor.

Obviously I could check to see if it is non-NULL, but that still will
not necessarily tell me anything.

For example:

/* here is a constructor car that takes an engine class as an
argument. But, I better check to make sure that engine is valid
so how do I do that?
*/
Car::Car( Engine* engine )
{

// check to make sure that engine is valid.
}
Thanks in advance for any help,
John
Jul 22 '05 #1
18 1333
In article <j2********************************@4ax.com>, fi******@airmail.net wrote:
How can I check to make sure that the object is good/valid that is
being passed into the constructor.

Obviously I could check to see if it is non-NULL, but that still will
not necessarily tell me anything.

For example:

/* here is a constructor car that takes an engine class as an
argument. But, I better check to make sure that engine is valid
so how do I do that?
*/


What do you mean by "valid" ? The Engine class should be responsible for making
sure that Engine objects are not "invalid".

Since you are passing in a pointer, you need to check for a null pointer.

If the pointer is not null, it's the callers responsibility to pass in a valid
pointer. There's no way to check whether a pointer is "wild" or not.

Cheers,
--
Donovan Rebbechi
http://pegasus.rutgers.edu/~elflord/
Jul 22 '05 #2
<fi******@airmail.net> wrote in message
news:j2********************************@4ax.com...
Hello,

I have a question about passing an object into a constructor.

How can I check to make sure that the object is good/valid that is
being passed into the constructor.

Obviously I could check to see if it is non-NULL,
Unless it's a pointer there's nothing to check, NULL-wise.
but that still will
not necessarily tell me anything.

For example:

/* here is a constructor car that takes an engine class as an
argument. But, I better check to make sure that engine is valid
so how do I do that?
*/
Car::Car( Engine* engine )
{

// check to make sure that engine is valid.


You'll have to ask the Engine object, if it has a member that serves that
purposes. Other than checking whether the supposed memory the object
occupies is real memory, which is a system-specific matter and OT here,
there is no general way to tell if an object is valid. If the Engine itself
can't tell you it's valid, nothing else can.

DW

Jul 22 '05 #3
fi******@airmail.net wrote:
I have a question about passing an object into a constructor.

How can I check to make sure that
the object that is being passed into the constructor is good/valid.

Obviously I could check to see if it is non-NULL
but that still will not necessarily tell me anything.

class Engine {
private:
// representation
const
unsigned int Valid;
public:
//functions
bool valid(void) const {
return 0x55555555 == Valid;
}
// constructors
Engine(void): Valid(0x55555555) { }
~Engine(void) { Valid = 0xAAAAAAAA; }
};
For example:

// Here is a constructor car
// that takes an engine class as an argument.
// I had better check to make sure that engine is valid.
// How do I do that?

Car::Car(const Engine& engine) {
// check to make sure that engine is valid.
if (engine.valid()) {
// Initialize *this.
}
else { /* Handle error. */ }
}


Jul 22 '05 #4
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:40**************@jpl.nasa.gov...
fi******@airmail.net wrote:
I have a question about passing an object into a constructor.

How can I check to make sure that
the object that is being passed into the constructor is good/valid.

Obviously I could check to see if it is non-NULL
but that still will not necessarily tell me anything.

class Engine {
private:
// representation
const
unsigned int Valid;
public:
//functions
bool valid(void) const {
return 0x55555555 == Valid;
}
// constructors
Engine(void): Valid(0x55555555) { }
~Engine(void) { Valid = 0xAAAAAAAA; }
};


Of course, with the same "valid" value used in all instances, and perhaps in
other classes as well, it will greatly increase the probability that some
dangling or uninitialized pointer will be unlucky enough to point somewhere
such that the Valid member happens to be 0x55555555.

DW

Jul 22 '05 #5

<fi******@airmail.net> skrev i en meddelelse
news:j2********************************@4ax.com...
Hello,

I have a question about passing an object into a constructor.

How can I check to make sure that the object is good/valid that is
being passed into the constructor.

Obviously I could check to see if it is non-NULL, but that still will
not necessarily tell me anything.

For example:

/* here is a constructor car that takes an engine class as an
argument. But, I better check to make sure that engine is valid
so how do I do that?
*/
Car::Car( Engine* engine )
{

// check to make sure that engine is valid.
}
Thanks in advance for any help,
John

Most probably, you need to not use a pointer:

Car::Car(Engine const& engine)

as this will assure a proper engine-object to be passed always.

If "Car" does not need an engine, you could keep your present design.

If Car needs to use an engine, but you for some reason want to keep the
signature of the constructor (the reason for this would not be based in the
language), You should throw from the constructor:

Car::Car( Engine* engine)
{
if (!engine) throw 0; // have a proper exception here!!
// continue construction here
}

but be prepared to refactor later.

I can't really recommend Tisdales trick unless there is a compelling reason
to do it that way (e.g. if you are not allowed to throw an exception in the
constructor).

/Peter
Jul 22 '05 #6

<fi******@airmail.net> wrote in message
news:j2********************************@4ax.com...
Hello,

I have a question about passing an object into a constructor.

How can I check to make sure that the object is good/valid that is
being passed into the constructor.

Obviously I could check to see if it is non-NULL, but that still will
not necessarily tell me anything.

[SNIP]

Well, the whole problem arises from the word "valid". It depends very much
what you define as a valid object. Testing for NULL is a way of checking
whether a pointer is valid but this doesn't tell you whether the object,
which this pointer points to, has a "valid = reasonable" state. If you just
want to check whether the pointer has something to point to then this NULL
test is fine. Otherwise you will have to define what characterizes a
"good/valid" object state and supply some function to check this. (See
Robert Tisdale's post).

Cheers
Chris
Jul 22 '05 #7
<fi******@airmail.net> skrev i meddelandet
news:j2********************************@4ax.com...
Hello,

I have a question about passing an object into a constructor.

How can I check to make sure that the object is good/valid that is
being passed into the constructor.


Why would you like to do that?
IMHO the right way to do it is that in the documentation of the class say
something as:

Car::Car( Engine* engine )
Precondition: engine points to a valid Engine object.

and leave the responsibility for this to the caller. This is the approach
the standard library has.

For example:
18.6.2.3 set_unexpected
unexpected_handler set_unexpected(unexpected_handler f) throw();
1 Effects: Establishes the function designated by fas the current
unexpected_handler.
2 Requires: f shall not be a null pointer.

--
Dag Henriksson
Jul 22 '05 #8
In article <j2********************************@4ax.com>,
fi******@airmail.net wrote:
Hello,

I have a question about passing an object into a constructor.

How can I check to make sure that the object is good/valid that is
being passed into the constructor.

Obviously I could check to see if it is non-NULL, but that still will
not necessarily tell me anything.

For example:

/* here is a constructor car that takes an engine class as an
argument. But, I better check to make sure that engine is valid
so how do I do that?
*/
Car::Car( Engine* engine )
{

// check to make sure that engine is valid.
}


In other words, you want to guard against someone doing something like:

Car myCar( (Engine*) 0x543562 );

(where 0x543562 doesn't point to an actual Engine object.) Or some such?

There isn't much you can do about this, but here is one idea:

class Engine {
static std::set< Engine* > allEngines;
public:
static bool isValid( Engine* anEngine ) {
return allEngines.count( anEngine ) == 1;
}

Engine() {
allEngines.insert( this );
}
~Engine() {
allEngines.erase( this );
}
};

Now:

Car::Car( Engine* engine ) {
assert( Engine::isValid( engine ) );
//...
}

This is not a cheep operation! It will probably slow your program down
tremondusly if you do this with every class. Be sure to make it so you
can define the extra code out when you build a release version.
Jul 22 '05 #9

"Daniel T." <po********@eathlink.net> skrev i meddelandet
news:po******************************@news02.east. earthlink.net...
In other words, you want to guard against someone doing something like:

Car myCar( (Engine*) 0x543562 );

(where 0x543562 doesn't point to an actual Engine object.) Or some such?

There isn't much you can do about this, but here is one idea:


Your idea will probably work on some implementation, but technically is the
effect of using an invalid pointer value undefined and could cause a
system-generated runtime fault.

That means that you can not check if a pointer argument is valid or not
inside a function (or anywhere else). When the pointer is passed to the
function (by value) we have already invoked undefined behavior.

--
Dag Henriksson
Jul 22 '05 #10

"Peter Koch Larsen" <pk*@mailme.dk> wrote in message
news:40*********************@dread14.news.tele.dk. ..
If Car needs to use an engine, but you for some reason want to keep the
signature of the constructor (the reason for this would not be based in the language), You should throw from the constructor:

Car::Car( Engine* engine)
{
if (!engine) throw 0; // have a proper exception here!!
// continue construction here
}

but be prepared to refactor later.

I can't really recommend Tisdales trick unless there is a compelling reason to do it that way (e.g. if you are not allowed to throw an exception in the constructor).


Yeah, but there is also the requirement that the pointer is "good/valid".
Depending on what the OP meant, your check doesn't guarantee that either.
Jul 22 '05 #11
Chris Theis wrote:
Well, the whole problem arises from the word "valid".
It depends very much what you define as a valid object.
Testing for NULL is a way of checking whether a pointer is valid
but this doesn't tell you whether the object to which
this pointer points has a "valid = reasonable" state.
If you just want to check
whether the pointer has something to point to,
then this NULL test is fine.
Otherwise, you will need to define
what characterizes a "good/valid" object state
and supply some function to check this.
(See Robert Tisdale's post).


A NULL pointer is valid pointer which always points to
an invalid object of any type.
There is, unfortunately, *no* way to determine whether
any other pointer (valid or not) references a valid object.
If every attempt to access an invalid object through a pointer
resulted in a segmentation fault, a bus error
or some other system error, there would be no problem.
The problem is that your program may access
and, perhaps, corrupt other valid data in your program.
It may also access an object that you have already deleted
but which has not been reallocated and reinitialized
so you must stamp it with a bit pattern which marks it invalid
when the program calls your constructor.

Jul 22 '05 #12
"Dag Henriksson" <da************@quidsoft.se> wrote in message news:<bu************@ID-200546.news.uni-berlin.de>...
[snip of a "registering new'ed objects" system]
Your idea will probably work on some implementation, but technically is the
effect of using an invalid pointer value undefined and could cause a
system-generated runtime fault.

That means that you can not check if a pointer argument is valid or not
inside a function (or anywhere else). When the pointer is passed to the
function (by value) we have already invoked undefined behavior.


Is it still undefined behaviour if I never dereference the pointer?
I agree it is certainly undefined if I try to access memory an
invalid pointer points at as though it were valid. But simply passing
an invalid pointer value through a function call is undefined?
Just checking...
Socks
Jul 22 '05 #13

<pu*********@hotmail.com> wrote in message news:c7**************************@posting.google.c om...

Is it still undefined behaviour if I never dereference the pointer?
I agree it is certainly undefined if I try to access memory an
invalid pointer points at as though it were valid. But simply passing
an invalid pointer value through a function call is undefined?
Just checking...


Yes it is. It's possible (though I've never seen a machine where this
happens) where merely copying an out of range pointer might trap.

Jul 22 '05 #14
Dag Henriksson wrote:
Your idea will probably work on some implementation, but technically is the
effect of using an invalid pointer value undefined and could cause a
system-generated runtime fault.

That means that you can not check if a pointer argument is valid or not
inside a function (or anywhere else). When the pointer is passed to the
function (by value) we have already invoked undefined behavior.


I think that you missed the point.
A system-generated runtime fault can be trapped
and your program can recover or abort.
The problem occurs when no fault is generated
and your program initializes a Car object with an invalid Engine object.

Jul 22 '05 #15
David White wrote:


Of course, with the same "valid" value used in all instances, and perhaps in
other classes as well, it will greatly increase the probability that some
dangling or uninitialized pointer will be unlucky enough to point somewhere
such that the Valid member happens to be 0x55555555.


You can be unlucky in many ways, but the scheme above in my
experience catches 99.99999% of bugs due to accessing
deleted objects. And they are usually caught the first time
the offending code is exercised. Personally I'd assert the
validity in every method too.

Jul 22 '05 #16

"jeffc" <no****@nowhere.com> skrev i en meddelelse
news:40********@news1.prserv.net...

"Peter Koch Larsen" <pk*@mailme.dk> wrote in message
news:40*********************@dread14.news.tele.dk. ..
If Car needs to use an engine, but you for some reason want to keep the
signature of the constructor (the reason for this would not be based in

the
language), You should throw from the constructor:

Car::Car( Engine* engine)
{
if (!engine) throw 0; // have a proper exception here!!
// continue construction here
}

but be prepared to refactor later.

I can't really recommend Tisdales trick unless there is a compelling

reason
to do it that way (e.g. if you are not allowed to throw an exception in

the
constructor).


Yeah, but there is also the requirement that the pointer is "good/valid".
Depending on what the OP meant, your check doesn't guarantee that either.


Well... there is no way to check if a pointer is valid in C++. It better
always be.

/Peter
Jul 22 '05 #17
> > How can I check to make sure that
the object that is being passed into the constructor is good/valid.
class Engine {
private:
// representation
const
unsigned int Valid;
public:
//functions
bool valid(void) const {
return 0x55555555 == Valid;


Signed-unsigned comparison.
}
// constructors
Engine(void): Valid(0x55555555) { }
~Engine(void) { Valid = 0xAAAAAAAA; }
};


I thought this was a troll at first, but others seem to have replied
to it seriously. Any standards-conforming compiler could optimise
away valid() entirely:

If UB has not been invoked, then valid() must return true.
If UB has been invoked, the program can do anything (specifically,
make valid() return true).

NB. I am ignoring (as you have) the case 0x55555555 > UINT_MAX.
However I suspect in this case valid() would always be false,
hence it can be optimised away still.

NB2. In a newsgroup for Standard C++, I think this construct
is fairly off-topic.
Jul 22 '05 #18
Old Wolf wrote:

I thought this was a troll at first, but others seem to have replied
to it seriously. Any standards-conforming compiler could optimise
away valid() entirely:


Only if someone has been silly enough to inline it. The example just
gives a flavour of how one might test the objects pulse. Mostly 'valid'
would be a class, with all its members defined outline, and an
assert_ok() method which asserts on failure.
Jul 22 '05 #19

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

Similar topics

4
by: Andrew | last post by:
Is it possible a constructor of a class to use a funtion defined in the same class ????
4
by: Colin McGuire | last post by:
Hi, I have a class with lots of constructors - one is shown below Public Sub New(ByVal rows As Integer, ByVal columns As Integer) InitializeComponent() 'And code in here that sets instance...
10
by: Kevin Buchan | last post by:
I searched the news group and could not find an answer to this question, so I'll go ahead and post it. Let's say I have a class A with a couple different constructors... nothin' special. Now,...
8
by: Lüpher Cypher | last post by:
Hi, Suppose we have a hierarchical class structure that looks something like this: Object | +-- Main | +-- Object1
15
by: Sam Kong | last post by:
Hello! I got recently intrigued with JavaScript's prototype-based object-orientation. However, I still don't understand the mechanism clearly. What's the difference between the following...
5
by: Michael Moreno | last post by:
Hello, In a class I have this code: public object Obj; If Obj is a COM object I would like to call in the Dispose() method the following code: ...
7
by: Markus Svilans | last post by:
Hello, My question involves virtual functions and inheritance. Suppose we have a class structure, that consists of "data" classes, and "processor" classes. The data classes are derived from...
2
by: Jeroen | last post by:
Hi all, I wrote a little bit of code to see the behaviour of (copy) constructors of base and derived classes. But I have a question about it. Let me explain by the following...
55
by: tonytech08 | last post by:
How valuable is it that class objects behave like built-in types? I appears that the whole "constructor doesn't return a value because they are called by the compiler" thing is to enable...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...

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.