0

I ran into a code yesterday, like this:

#include <stdio.h>
using namespace std;

class test {
public:
    test()
    {
        printf("This is test's construct\n");
    }

    ~test()
    {
        printf("This is test's destroy\n");
    }
};

int main()
{
    test t(); // no output
    return 0;
}

when I run this program, no output

But if I change

test t();

into

test t;

the output is as follows

This is test's construct
This is test's destroy

So I want to ask why the first example has no output?

cigien
  • 57,834
  • 11
  • 73
  • 112
  • 2
    `test t();` declares a function returning a test object. Some info here: [https://www.fluentcpp.com/2018/01/30/most-vexing-parse/](https://www.fluentcpp.com/2018/01/30/most-vexing-parse/) – drescherjm Jul 07 '20 at 02:09
  • And compiling with proper warnings enabled should have flagged it. At least I know clang will warn about this. I am under the impression that gcc is less capable here. – sweenish Jul 07 '20 at 02:13

1 Answers1

3
test t();

is a declaration of a function named t that takes no arguments and returns a test object.

test t;

defines an object t, and calls its default constructor.

In general, prefer to initialize objects like this:

test t{};

so that you avoid any ambiguities.

cigien
  • 57,834
  • 11
  • 73
  • 112