Reputation: 10507
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.
Upvotes: 0
Views: 120
Reputation: 110658
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.
Upvotes: 3
Reputation: 81349
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
.
Upvotes: 2
Reputation: 545528
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.
Upvotes: 2
Reputation: 110069
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
.
Upvotes: 8