1

I saw this question about constructors and I don't understand why the variable a is calling the constructor.

I thought it wass an error because the variable declaration is out of main without stating global before the name of it and they only wrote a; without the class name before it. How does the compiler know that the variable is of type Test?

#include <iostream>
using namespace std;

class Test
{
public:
      Test() { cout << "Hello from Test() "; }
} a;
 
int main()
{
    cout << "Main Started ";
    return 0;
}

The answer for the output was - "Hello from Test() Main Started".

Holt
  • 36,600
  • 7
  • 92
  • 139
Dudu Gvili
  • 37
  • 6
  • 4
    "without stating global before the name of it" ? you mean `global Test a;` ? Something like that does not exist in C++. Seems like you could use a [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – 463035818_is_not_an_ai Oct 11 '21 at 09:30
  • 4
    The class name actually *is* there: `class Test a;` is an almost valid short hand pre-declaration of class and variable at the same time (almost because you cannot declare objects of incomplete type), equivalent to `class Test; Test a;`. Placing the class definition in between doesn't change anything about apart from that the type now is complete, making the whole stuff fully legal. It's not a recommended way to declare variables, though. – Aconcagua Oct 11 '21 at 09:36
  • 3
    Side note: [about `using namespace std`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)... – Aconcagua Oct 11 '21 at 09:38

1 Answers1

6

As you might know, we have two ways to create an object from the Test class:

first, in the main:

class Test
        {
        public:
            Test() { cout << "Hello from Test() "; }
        };

int main()
{
    Test a;
    cout << "Main Started ";
    return 0;
}

Or before starting main in the definition of your class (like your code):

class Test
{
public:
      Test() { cout << "Hello from Test() "; }
} a;
 
int main()
{
    cout << "Main Started ";
    return 0;
}

In both cases, you are calling the constructor of the Test class once you make an object from it. In the main or before it.