Thread View: gnu.g++.help
1 messages
1 total messages
Started by Mary Ann Brennan
Tue, 08 Sep 1992 20:37
using cout in a constructor (Q)
Author: Mary Ann Brennan
Date: Tue, 08 Sep 1992 20:37
Date: Tue, 08 Sep 1992 20:37
91 lines
2407 bytes
2407 bytes
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
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads