using cout statements in ctor and dtor

S

subramanian100in

Long back I posted a program followed by a question to this discussion
group comp.lang.c++. I don't remember which post that was. In that
program, I had used cout statements in the ctor and dtor. Some
knowledgeable gentlemen in this forum, questioned regarding the usage
of cout statements in ctor and dtor. I am unable to understand why
cout statements should NOT be used in ctor and dtor.

My question: Should the usage of cout statements be avoided in ctor
and dtor ? If so why ?

Kindly explain.

Thanks
V.Subramanian
 
J

Jorgen Grahn

(e-mail address removed), India ha scritto:


Generally, yes.


Because it's a side effect, mixing different concerns.


For example, what happens if you later want to reuse the class in a GUI
application?

He removes the cout << foo, I suppose. IOW, I don't think that's a
valid argument unless you're a library writer, and almost noone is.

Your first argument is valid, I think: you generally don't want
constructors to change global state with wide visibility, such as cout
or other global, highly visible data. And it's maybe a sign that you
focus too much on few, big objects which cannot be copied, rather than
on small classes with value semantics.

/Jorgen
 
S

Stefan Ram

Jorgen Grahn said:
He removes the cout << foo, I suppose.

Then, it would become another class. If the constructore
prints something, this should be stated in its
documentation. Not only would it not work in a GUI
application, but it also would disturb any other output:
For example, the main program might just be in the middle of
the process of printing a table, when suddenly some garbage
text is written destroying the table layout, just because
the main process constructed an object?

When the print action is documented, clients will assume
it for their work, then it can not easily be removed again
form the class without breaking the clients.
IOW, I don't think that's a
valid argument unless you're a library writer, and almost noone is.

Almost everyone is. Application design is library design,
when done properly - with one exception: the main function.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top