C + + Primer Plus Sixth Edition notes

Source: Internet
Author: User

C + + Primer Plus Sixth Edition notes

Thinking about Object declaration

Transferred from: http://www.cnblogs.com/weiqubo/archive/2009/11/02/1930042.html

What is the difference between the syntax for defining an object in C + + with parentheses and without parentheses?

  1. #include <iostream>
  2. Class MyClass
  3. {
  4. Public
  5. MyClass ()
  6. {
  7. Std::cout << "Hello myclass!" << Std::endl;
  8. }
  9. Public
  10. void MyMethod ()
  11. {
  12. Std::cout << "Hello mymethod!" << Std::endl;
  13. }
  14. };

If this defines the object: MyClass obj; Then its constructor will be executed if obj is called. MyMethod (); it will execute correctly.
However, if you have parentheses: MyClass obj (); Then its constructor will not be executed, calling obj. MyMethod (); Syntax errors also occur, what is the syntax for defining obj?

MyClass obj () defines obj as a syntax that defines a parameterless function named obj with the type MyClass class (that is, the return value is MyClass type).

In addition, if the dynamic heap allocation is to be parenthesized, such as MyClass *obj = new MyClass () will not error (but, in the vc6.0 does not add () No error, and the result is the same, the reason to be solved? However, if a constructor with parameters is defined in the class, it is definitely wrong to define the class without parentheses #add to avoid errors, uniform parentheses are good)

C + + Primer Plus Sixth Edition notes

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.