Creating an object that is read from an input stream.

D

David White

Jason Heyes said:
What about the box centered at the origin -1,1,1,-1? Isn't that an obvious
default to use?

If you like. The lengths are 2 rather than 1, which doesn't seem an obvious
default to me. But it really doesn't matter.
have

And if there isn't a reasonable default, you start to think that there is
something wrong with your class. What's worse is when you have a default
that doesn't make any sense, and your are using it throughout your
program.

I explained the usefulness of a default constructor as well as I could last
time. The values chosen are not as important as the convenience of being
able to create a Box, or whatever, first, and fill in the right values
later.
If you declare objects as you use them, you won't have a problem. For
instance, rather than write

Box box;
// code fragment
box = whatever;

Not always possible. In the case of the LogRect and VirRect members
described above, the correct values sometimes have to be computed using map
objects (for mapping one scale to another). The drawable object's
initializor list is too early to initialize all its members to their final
values.
you can write

// code fragment
Box box = whatever;

This way you don't abuse the default constructor.

Good luck to you if you can write an application of any complexity without
ever needing to construct a default object and fill in the correct values
later.
It's the simple classes that tend to be used the most, and for which a
default constructor is most useful.

Even for simple classes such as Box, however, a default constructor is a bad

Fine.

[snip]
Box b;
if(is >> b)
{
// whatever
}

DW

You create a default Box and then write straight over it. The default Box
was never used.

It's only a "default" Box because you insisted that it always be a valid
Box. The default constructor could do nothing at all if you think it's
wasteful to "write straight over" the default valid Box.
Therefore it should never have been created. Here is a
correct version that does not use the default constructor:

It's an alternative version anyway.
int l, r, u, d;
if (is >> l >> r >> u >> d)
{
Box b(l, r, u, d);
// whatever
}

I'd rather create one object and read it in than create four objects, read
them all in, and then pass them to the constructor of a fifth object.

DW
 
J

Jason Heyes

Sorry if I sounded strict in my last reply. I was just trying to make my
point clear. Its no big deal really. Default constructors or no default
constructors. What does it matter? ;)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,121
Latest member
LowellMcGu
Top