1

Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

I have a very simple C++ class "A", whose empty constructor is invoked in main. The one and only empty c'tor just throws an exception SomeException.

#include <iostream>
using namespace std;


class SomeException : public exception { };


class A {

public:
    A() {
        throw SomeException();
    }

};

int main() {
    try {
        //A a();
        A a;
        cout << "No exception." << endl;
    }
    catch (SomeException& se) {
        cout << "Caught se." << endl;
    }
}

When I invoke A's constructor with no parantheses like below, it correctly throws the intended exception.

A a;

The output in this case is:

$ ./a.exe
Caught se.

But if I invoke the c'tor with the below syntax, it doesn't throw exception, and continues to next line, as though nothing happened!

A a();

The output in this case is...

$ ./a.exe
No exception.

I tried the above program on Ubuntu 11.10 and also on windows usign minGW, and both give identical results. I am using GCC version 4.5.2 for minGW and 4.6.1 for Ubuntu.

Any clues about this strange behavior? Is this a bug in gcc, or is my way is incorrect?

Community
  • 1
  • 1
Mopparthy Ravindranath
  • 3,014
  • 6
  • 41
  • 78

1 Answers1

5
A a();

is a function declaration, not an object instantiation. No object is constructed, no constructor is called, no exception thrown.

It's called most vexing parse.

It's not a bug, it's perfectly fine.

These two:

A a();
A b;

are not equivalent. The second creates an object of type A called b. The first declares a method called a that takes no arguments and returns A.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625