home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!haven.umd.edu!darwin.sura.net!seismo!brennan
- From: brennan@seismo.CSS.GOV (Mary Ann Brennan)
- Newsgroups: gnu.g++.help
- Subject: using cout in a constructor (Q)
- Message-ID: <51201@seismo.CSS.GOV>
- Date: 8 Sep 92 20:37:39 GMT
- Sender: usenet@seismo.CSS.GOV
- Organization: Center for Seismic Studies, Arlington, VA
- Lines: 91
- Nntp-Posting-Host: tenso.css.gov
-
-
- Apologies for the length, I couldn't find any other postings that helped me.
- I'm trying to teach myself C++ and am reading Stroustrup's
- "The C++ Programming Language" Reprinted with corrections July 1987.
-
- On p. 167 exercise 12 is:
- Given the program:
-
- #include <stream.h>
-
- main()
- {
- cout << "Hello, world\n" ;
- }
-
- modify it to produce the output
-
- Initialize
- Hello, world
- Clean up
-
- Do not change main() in any way.
-
- on pp. 158-9 Stroustrup discusses static store and suggests inventing
- a type with a constructor and destructor for initialization and cleanup
- to be used only once to allocate a static object so the constructor
- and destructor are called.
-
- my first attempt used streams as follows:
-
- // startend1.h
-
- class startend {
- int *junk;
- public:
- startend() { junk = new int; cout << "Initialize\n"; }
- ~startend() { delete junk; cout << "Clean up\n"; }
- };
-
- // hello1.c
- #include <stream.h>
- #include "startend1.h"
-
- static startend bookkeep;
-
- main()
- {
- cout << "Hello, world\n" ;
- }
-
- it had a segmentation fault (it appeared to die while running the constructor
- and that cout may not have been initialized before used -- surmised by stepping
- through with adb, dbx didn't seem to like g++).
-
- After fiddling with it for a bit, I gave up on streams and changed to stdio:
-
- // startend2.h
-
- class startend {
- int *junk;
- public:
- startend() { junk = new int; printf("Initialize\n"); }
- ~startend() { delete junk; printf("Clean up\n"); }
- };
-
- // hello2.c
- #include <stream.h>
- #include "startend2.h"
-
- static startend bookkeep;
-
- main()
- {
- cout << "Hello, world\n" ;
- }
-
- which produced the intended result without core dumping:
-
- Initialize
- Hello, world
- Clean up
-
- my questions:
- Why doesn't the first version work?
- Is there any way to use streams inside a constructor?
- More generally, what do I seem to be misunderstanding?
-
- Thanks in advance,
- Mary Ann Brennan
-
- brennan@seismo.css.gov
-