简体   繁体   中英

c++ constructors differences

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.

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 .

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.

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM