Today I was asked how to print "hello, world" without the execution of the main function.
I failed to answer it and was told that I should consider to define a "const static" function which prints "hello, world".
I only know that a static function inside a class can be called outside it even if it is a private one. But how should const static function related to print "hello, world" without execution of the main function.
Peter87
Nice. How is that working? I thought that cout<< returned a reference to an ostream and you are assigning that to a void *, so could you explain how it is working?
The cout part returns a stream object that is implicitly converted to a void* when assigned to the void pointer. Longer explanation follows ...
operator<< returns a reference to the stream object, in this case std::cout. This is what makes it possible to have multiple << but only std::cout once at the beginning of the row.
Streams have operatorvoid*() that allows them to be implicitly converted to a void pointer: http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/ This is a hack to allow easy testing if any error flag is set: if (std::cout) {std::cout << "Nothing wrong with cout!"} This is mostly useful when reading from a stream. _ is the name of the void* variable.
It appears that operatorvoid*() was changed in C++11 to explicitoperatorbool() so I don't think the code will work in C++11. I didn't know this when I wrote the code. To make it work in C++11 you can replace void* with std::ostream& or auto.
@subjugater, what histrungalot has done is used a constructor. When he initialized a global variable myclass of the type "thing", it made a call to the constructor, which then printed a certain message, before the main could execute...
I don't know if this would work on modern compilers, but it was there in the book from which I learnt C++. You could use something like #define start and #define end...
EDIT: Also, Peter87, you're simply brilliant.. (I did not understand much of what you did there, but still, it looks damn impressive!)... I wish to learn more from you over these forums, as much as possible... :)