Today, I casually raised a simple question in the group:A class with default constructor. When constructing an instance of this class on the stack, do I need to add a pair of null parentheses after the variable name?
There are three answers:
- No need or empty brackets
- Parentheses should be added
- Can be added or not added, with the same effect
Obviously, only 1st answers are correct. If the question is followed:What will happen if empty parentheses are added? Does the compiler report an error or make it pass compilation smoothly?
Some people think that adding null parentheses is a syntax error. In fact, there is no error in the syntax alone. This is a statement that fully complies with the Syntax:
001 class Foo {
002 public:
003 void execute ();
004 };
005...
006 void bar (){
007 Foo F1; // Construct an instance of the foo object on the stack, named F1
008 Foo F2 (); // Correct syntax: declare a function prototype, which has no parameters and returns a foo instance.
009 f1.execute ();
010 f2.execute (); // Compilation Error
The above exampleCode, Row 7th is the correct syntax for "constructing an instance of the foo class on the stack", but the meaning of row 8th has completely changed, even though its syntax is correct, without the following 010th sentence, the compiler will only give a warning that you declare a function prototype, but do not use this function, for example, you can intelligently guess whether you want to construct an object instance but add empty brackets with errors. If there are 010th sentences, the compiler will report a compilation error in the 010 sentence, obviously, F2 is just a function name, not a class, structure, or union instance ).