3

I created a class which basically serves as a public structure in this example, and let's say the class name is X. I want to declare a local object in main function. The short version of my question is: I know we can do X foo;, but I think X foo(); (attach a pair of parenthesis) should work, and I thought the first usage is actually a shorthand of the second usage. The entire code is provided below:

#include <iostream>

using namespace std;

class X {
    public:
        int val1;
        int val2;
};

int main() {
    X a;
    X b();    // A warning here
    X *c = new X;
    X *d = new X();

    cout << "val of a: " << a.val1 << " " << a.val2 << endl;
    cout << "val of b: " << b.val1 << " " << b.val2 << endl;    // Compile error
    cout << "val of c: " << c->val1 << " " << c->val2 << endl;
    cout << "val of d: " << d->val1 << " " << d->val2 << endl;

    return 0;
}

And the compiler complains:

11_stack.cpp:16:6: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse]
        X ab();
            ^~
11_stack.cpp:16:6: note: replace parentheses with an initializer to declare a variable
        X ab();
            ^~
            {}
11_stack.cpp:22:26: error: use of undeclared identifier 'b'
        cout << "val of b: " << b.val1 << " " << b.val2 << endl;
                                ^
11_stack.cpp:22:43: error: use of undeclared identifier 'b'
        cout << "val of b: " << b.val1 << " " << b.val2 << endl;
                                                 ^
1 warning and 2 errors generated.

My initial guesses are the following:

  1. In any case, we shouldn't put an empty parenthesis after a declared variable.
  2. It triggers operator().

But later on I disproved both hypotheses. We can see the first disproof in the code: both X *c = new X; and X *d = new X(); work. For the second one, I put additional code like this:

a();

Then I got compilation error messages:

11_stack.cpp:26:2: error: type 'X' does not provide a call operator
        a();
        ^

So what exactly cause the error?

Working environment:

  • Mac OS 10.11.3
  • g++ with flag c++11
  • Xcode Version 7.2 (7C68)

P.S. Please also help me think a better and descriptive post title if it's too ambiguous...

Jarod42
  • 203,559
  • 14
  • 181
  • 302
TimeString
  • 1,778
  • 14
  • 25

1 Answers1

0

c and d are pointers, so you need c->val1 instead of using ..

javad
  • 498
  • 4
  • 15