Create an instance of a class with or without parentheses?

#include <iostream>
using namespace std;

class CTest 
{
    int x;

  public:
    CTest()
    { 
       x = 3;
       cout << "A"; 
    }
};

int main () {
  CTest t1;
  CTest t2();

  return 0;
}

CTest t1 prints "A" of course.

But nothing seems to happen with t2 (), but the code works well.

So do we use these parentheses with no arguments? Or why can we use it that way?

+6
source share
1 answer

This is a fad of C ++ syntax. Line

CTest t1;

declares a local variable of type CTestnamed t1. It implicitly calls the default constructor. On the other hand, the line

CTest t2();

, t2, CTest. , t2, , .

, .

++ 11

CTest t2{};

.

, !

+16

All Articles