What is the syntax for defining objects in C + +, and what is the difference between parentheses and no parentheses?

Source: Internet
Author: User

#include <iostream> class MyClass {Public:myclass () {std::cout << "Hello myclass!" << Std::endl;} PU Blic:void MyMethod () {std::cout << "Hello mymethod!" << Std::endl;};

If this defines the object: MyClass obj; Then its constructor will be executed if obj is invoked. MyMethod () is also performed correctly.
But if with parentheses: MyClass obj (); Then its constructor is not executed, call obj. MyMethod (), there will also be syntax errors, this syntax is the definition of obj what is.

MyClass obj () defines obj as what is syntactically defined as a parameterless function named obj, the type MyClass class (that is, the return value is of type MyClass).

In addition, if the dynamic heap allocation is to be parenthesized, such as MyClass *obj = new MyClass () does not add an error (but, in the vc6.0 does not add () and no error, and the result is the same, the reason to be solved. However, if a class has a constructor defined with parameters and does not define a default constructor (at which point the compiler no longer generates a default construct), it is certainly wrong to define the class without parentheses #add to avoid errors, uniform braces are wonderful.

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.