Changing C++ output without changing the main() function [closed]

Ok, fixing your main function and iostream.h … This is the way

#include <iostream>

// to make sure std::cout is constructed when we use it
// before main was called - thxx to @chappar
std::ios_base::Init stream_initializer;

struct caller {
    caller() { std::cout << "I "; }
    ~caller() { std::cout << " You"; }
} c;

// ohh well, for the br0ken main function
using std::cout;

int main()
{
    cout<<"Love";
}

I figured i should explain why that works. The code defines a structure that has a constructor and a destructor. The constructor is run when you create an object of the struct and the destructor is run when that object is destroyed. Now, at the end of a struct definition, you can put declarators that will have the type caller.

So, what we did above is creating an object called c which is constructed (and the constructor called) at program start – even before main is run. And when the program terminates, the object is destroyed and the destructor is run. In between, main printed “Love”.

That pattern actually is very well known by the term RAII which usually claims some resource in the constructor and releases it again in the destructor call.

Leave a Comment