The difference between parentheses and no parentheses when creating objects in C + + __c++

Source: Internet
Author: User

When an object is created in the original address C + + The difference between parentheses and parentheses
The syntax for creating objects in C + + is-–
1 creating MyClass A on the stack;
2 creates braces on the heap MyClass *a= new MyClass ();
3 without parentheses MyClass *a = new MyClass;
4. ————— MyClass A (); Declares a parameterless function with a return value of MyClass type.

#include <iostream> class MyClass {Public:myclass () {std::cout << "Hello mycl   
    ass! "<< Std::endl;   
    MyClass (int i): num (i) {std::cout << "Hello MyClass!------int" << Std::endl;   
    } void MyMethod () {std::cout << "output member num:" <<num << Std::endl;  
} private:int num;  
};  
    int main () {//---------------a constructor that uses no parameters or has a default parameter value for calling the constructor MyClass c1;//. MyClass C2 ()//does not invoke an parameterless constructor, in various cases, that declares a function that returns a value of type MyClass MyClass C3 (1); The constructor//that invokes parameter int/*---------------for new off  
    The difference between a key and parenthesis---1. There is no difference between a custom type and a default constructor of 2. For built-in types, parentheses are initialized with the */std::cout<<std::endl;  
    MyClass *c4 = new MyClass ();  
    C4->mymethod ();  
    MyClass *c5 = new MyClass (1);  
    C5->mymethod ();  
    MyClass *c6 = new MyClass;  

    C6->mymethod ();  
    Built-in type std::cout<<std::endl; Int*pint1 = new int (1);  
    int *pint2 = new int ();  

    int *pint3 = new int;  
    std::cout<<*pint1<< "" <<*pint2<< "" <<*pint3<<std::endl;  
return 0;   }

Results:

Conclusion: The New keyword creates an object for the built-in type: parenthesis is initialized without parenthesis, and for a custom type, the default constructor is invoked 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.