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
  • 9,640
  • 9
  • 43
  • 71

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
  • 101,717
  • 21
  • 254
  • 248
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
  • 104,685
  • 19
  • 232
  • 315
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
  • 506,650
  • 124
  • 909
  • 1,183
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
  • 78,684
  • 20
  • 152
  • 166