views:

182

answers:

4

Hi, I have a class made up of several fields, and I have several constructors. I also have a constructor that doesn't take any parameters, but when I try to use it:

int main {
    A a;
}

The compiler generates an error, while if I use it like this:

int main {
    A a();
}

It's ok. What's that?

Thank you

+11  A: 

The first main uses A's default constructor. The second one declares a function that takes no parameters and returns an A by value, which probably isn't what you intend.

So what does the definition of A look like and what is the error that the compiler generates?

Oh, and you need to provide a parameter list in the declaration of main: int main() { //... , not int main { //...

Charles Bailey
+2  A: 

By OK you mean it compiles or that it works? The line of code:

   A a();

is a declaration (or prototype) of a function named a that takes no parameters and returns an object of type A.

I think for anyone to have a chance to help you with your real problem you'll need to post at least the declaration for class A.

Michael Burr
A: 

You're both right, I had a problem inside the class.

tunnuz
+1  A: 

Charles and Michael Burr both identified that the second declaration was in fact a function prototype and not an instantiation of A.

As for possible reasons why your first code snippet did not work, you would get a compilation error in this situation when:

  1. Class A inherits from a base class that has no default constructor; OR
  2. Class A contains objects of types that have no default constructor; OR
  3. Class A contains reference members;

AND

You have provided a default constructor which omits one or more of these subobjects from its initialiser list.

All of these subobjects need some way to be initialised, and the default constructor produced by the compiler won't do it. Note that in all cases you need to initialise them in the initialiser list, not the body of the constructor.

j_random_hacker