Print Hello World with Empty or Blank Main in C++



In this problem, we will see how to print "Hello World" into the console, but we cannot write anything into the main function.

This problem can be solved in different ways. Initially, we will create a global variable, then we will store the returned value of the printf() function into that variable. When printf() is executed, then it will be printed.

You can print "Hello World" without using the logic inside the main() function in different ways, such as using Global Constructors,Class Object and macros, or preprocessor, etc.

Using Global Constructor

A global constructor is the constructor of a global object that runs before main(). If you add a print statement inside this constructor, it will be executed when the object is created, allowing you to print "Hello World" even with an empty main() function.

Syntax

Following is the output is as follows:

class Hello {
   public:
    Hello() {
        cout << "Hello World!" << endl;
    }
};
Hello obj;
int main() {}

Example

#include <iostream>
using namespace std;
class Hello {
  public:
    Hello() {
        cout << "Hello World!" << endl;
    }
};
Hello obj;
int main() {}

Following is the output to the above program:

Hello World!

Using a Class Object

A class object is an instance of a class that is created to use its properties and functions. So, if you add a print statement inside the constructor, it will execute when the object is instantiated without calling a main() function.

Syntax

Following is the output is as follows:

class Hello {
  public:
    Hello();
};
Hello::Hello() {
  std::cout << "Hello World!" << std::endl;
}
Hello h;
int main() {}

Example

#include <iostream>
using namespace std;
class Hello {
  public:
    Hello();
};
Hello::Hello() {
    cout << "Hello World!" << endl;
}
Hello h;
int main() {}

Following is the output to the above program:

Hello World!

Using Macros and Preprocessor

Using the preprocessor and macros, you can print "Hello World" with an empty main() function. To achieve this, we need to define a macro with #define that executes a print() statement before the main() function. The compiler then replaces the macro definition with actual code before compilation, allowing the output to be printed even though main() is blank.

Syntax

Following is the output is as follows:

#define H cout << "Hello World!" << endl;
class A {
public:
  A() { H }
};
A a;
int main() {}

Example

#include <iostream>
#define H cout << "Hello World!" << endl;
using namespace std;
class A {
public:
    A() { H }
};
A a;
int main() {}

Following is the output to the above program:

Hello World!
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-05-07T14:13:04+05:30

478 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements