/* ** $Id: insane.cc 619 2007-03-23 02:18:15Z phf $ ** ** Some crazy stuff, strictly for your entertainment. :-) */ #include #include using std::cout; using std::endl; // Remember how in C there was a difference between a function // defined with () and a function defined with (void)? Right, // the former could be called with *any* argument list, while // the latter could only be called with the empty argument list. // In C++ that's apparently fixed, at least for methods, so () // is now the same as (void), 100%. class One { public: One() { cout << "Default constructor!" << endl; } One(int i) { cout << "Integer constructor!" << endl; i = 1; } }; class Two { public: Two(void) { cout << "Void constructor!" << endl; } Two(int i) { cout << "Integer constructor!" << endl; i = 1; } }; // If you were sufficiently C-damaged, you might expect that // you can overload () versus (void), but of course you can't. // Funny thing about it is the error message. Comment out the // class Three below and try yourself. :-) /* class Three { public: Three() { cout << "Default constructor!" << endl; } Three(void) { cout << "Void constructor!" << endl; } }; */ // BTW, you'll get the same result with two () constructors // and two (void) constructors, showing that the two notations // are identical in C++. Good, it makes sense that way, it's // just that C is different and less sensible. int main(void) { // Alright, so when we make objects of these classes, we'd // expect the default constructor to get called. And it does, // in both cases. cout << "--- one ---" << endl; One one; cout << "--- two ---" << endl; Two two; // Step back for a second. Let's say we want both of these to // be initialized from an integer. Of course we'd write this: cout << "--- eins ---" << endl; One eins(1); cout << "--- zwei ---" << endl; Two zwei(2); // And of course the integer constructor gets called in both // cases. Hmm, so we can have no parenthesis or parenthesis // with an argument. What about just parenthesis with nothing // in between? Shouldn't that call the default constructor as // well? cout << "--- argh ---" << endl; One argh(); cout << "--- barf ---" << endl; Two barf(); // No output? None? What the heck is going on? Try to figure // it out yourself. If you get stuck, comment out the code // below and compile again, you should get it then. Yes, the // syntax of C and C++ is *really* horrible. :-) /* cout << "----------" << endl; cout << sizeof(One) << endl; cout << sizeof(one) << endl; cout << sizeof(argh) << endl; cout << sizeof(Two) << endl; cout << sizeof(two) << endl; cout << sizeof(barf) << endl; */ }