gerry@TOADWAR.UCAR.EDU (gerry wiener) (03/31/89)
I believe the following program should print Initialize Hello, world Clean up Instead it prints Hello, world Clean up If the definition of y is placed inside main(), then the program prints Initialize Hello, world Clean up ------------------------------------------------------------------------------ #include <stream.h> class x { public: x(); ~x(); }; x::x() { cout << "Initialize" << "\n"; } x::~x() { cout << "Clean up" << "\n"; } x y; main() { cout << "Hello, world\n"; }
cooper@gecrux.steinmetz.ge.com (Clark Cooper) (03/31/89)
In <8903301644.AA01395@toadwar.UCAR.EDU> gerry wiener writes: }I believe the following program should print } }Initialize }Hello, world }Clean up } }Instead it prints } }Hello, world }Clean up } }If the definition of y is placed inside main(), then the program prints } }Initialize }Hello, world }Clean up [followed by a program that has a class constructor that uses cout and then declares a global instance of the class] The gotcha here is that 'cout' is also a class object and has to be initialized. Since you don't have any guarantee about order of initialization of global objects, it is possible that object-y's constructor is called before cout's is. If you had used 'printf' instead of streams, you would have seen that y's constructor was in fact called. -- ====================================================== Clark Cooper cooper@gecrux.steinmetz.ge.com (518) 387-5887 coopercc@crd.ge.com ...!uunet!steinmetz!cooper