On Feb 12, 5:08 pm, "Wilson" <tpw...@googlemail.comwrote:
i am very new to c++ and am creating a new program, below are two
seperate parts of the program, made to run seperately, however the
constructor in one works (prints "constructing" on the screen), while
the constructor in the other doesnt. Can you please help me understand
why, i think they are almost identical.
This one works:
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
class Student
{
public:
Student()
{
cout << "constructing" << endl;
a = 0;
b = 0.0;
}
protected:
int a;
float b;
};
int main(int nNumberofArgs, char* pszArgs[])
{
cout << "Creating a new Student object" << endl;
Student s;
cout << "Creating a second student object" << endl;
Student t;
system("PAUSE");}
------------------------------------------------------------------------------------------------------------
this one doesnt:
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
class test
{
public:
test()
{
cout << "constructing";
b = 0;
a = 0;
}
protected:
int a;
int b;};
int main(int nNumberofArgs, char* pszArgs[])
{
cout << "Creating new test object" << endl;
test one;
cout << "creating second test object" << endl;
test two;
system("PAUSE");
}
It would seem that you're running into buffered output problems.
I'm assuming that PUAUSE is an external shell script or program that
sleeps for a bit so you can examine output.
Notice that you're not shifting std::endl into std::cout. std::endl
has a std::flush included in it, thus flushing the buffer.
To fix this, you can either include std::endl in the test constrctor,
use std::cerr, or a host of other options. On a side note, you should
usually use std::cerr for debugging like this. These buffered output
problems will can cause lots of headache.
On a rather minor detail, I believe std::cerr is actually line
buffered. But, most debugging output is done one a per line basis so
this really shouldn't be a big deal.
The program below demonstrates the problem a bit better. It will print
Constructing then wait 5 seconds before printing the second
constructing. This is because at program close, all file descriptors
are flushed. In your program I assume your using Ctrl-C to quite the
program which won't flush the file output, hence it appears to not be
printing.
#include <iostream>
class A
{
public:
A()
{
std::cout << "Constructing." << std::endl ;
}
} ;
class B
{
public:
B()
{
std::cout << "Constructing" ;
}
} ;
int
main( int argc, char* argv[] )
{
A a ;
B b ;
sleep( 5 ) ;
}
HTH,
Paul Davis