0

If I have the following class:

class A{
private:
  int x;
public:
  A(){
    x = 5;
  }
};

Whats the difference between these 2 declarations?

A a;

vs.

A a();

Thanks.

poy
  • 10,063
  • 9
  • 49
  • 74

4 Answers4

8
A a;

This creates an object of type A and calls the default constructor.

A a();

This declares a function called a that returns an object of type A.

interjay
  • 107,303
  • 21
  • 270
  • 254
3

Perhaps it is interesting to note, in addition to what others have said, that there is a difference between the following two lines:

A a;
A a{}; // Using uniform initialization from C++11 to avoid the ambiguity

And also between the following two lines:

A* a = new A;
A* a = new A(); // or new A{}

In the first line of each example, the object is default-initialized. In the second lines, the object is value-initialized. The difference is that while default-initialization will call the default constructor of A, value-initialization will zero-initialize the object first and then call the default constructor (if there are no user-provided constructors).

For anything that is not a class type, default-initialization will perform no initialization. For anything that is not a class type or is a union without a user-provided constructor, value-initialization will zero-initialize the object.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
2

The second code does not define an object called a, it declares a function a with return type A without arguments. This property of the C++ compiler is commonly known as the most vexing parse.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2
A a;

This declares an element of class A and constructs it using the default constructor.

A a();

This declares a function called a taking no parameters and returning an object of type A.

K-ballo
  • 80,396
  • 20
  • 159
  • 169