[Turn]c++ new with parentheses and without parentheses

Source: Internet
Author: User

ref:http://m.blog.csdn.net/blog/u012745772/42420443

When the new object is added (), there is no (), do not know what is the difference?
Like what:
CBase *base = new cderived ();
CBase *base = new cdeviced;

Many people say that parentheses call a constructor without arguments, and no parentheses call a default constructor or a unique constructor. That's a problem.
For the custom class type:
If the class does not have a constructor defined (the default constructor is synthesized by the compiler) and there is no virtual function, then Class C = new class; The default constructor for the composition is not called, and Class C = new Class (); The default constructor is called. The requested space is initialized to 0
If the class does not have a constructor defined (the default constructor is synthesized by the compiler) but has a virtual function, then Class C = New class, and Class C = new Class (), and the default constructor is called. The requested space is not initialized to 0
If the class defines a default constructor, then Class C = New class, and Class C = new Class (), the default constructor is called.

For built-in types:
int *a = new int, the requested int space is not initialized, and int *a = new int (); The int space requested is initialized to 0.
The difference between the following two statements is that the value in the first dynamic request space is a random value, the second one is initialized, and the value is 0:
int *p1 = new INT[10];
int *p2 = new INT[10] ();
Conclusion: Do not use new without parentheses.
Class a{
Public
A () {a=1;}
Public
int A;
};
A *a1=new A;
A *a2=new a ();

cout<<a1->a<<endl; Output: 842150451
cout<<a2->a<<endl; Output 0
A A3;
cout<<a3.a<<endl; Run exception, A is not initialized.
If you add a virtual, such as virtual ~a () {},
The
cout<<a1->a<<endl; Output: 842150451
cout<<a2->a<<endl; Output-842150451

[Turn]c++ new with parentheses and without parentheses

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.