Why can c ++ constructor of a class be a private member of a class? Confuse

Source: Internet
Author: User

See the following example.Program:

Class point <br/>{< br/> Public: <br/> point (INT xx = 0, int YY = 0) <br/>{< br/> X = xx; <br/> Y = YY; <br/>}< br/> point (point & P) <br/>{< br/> X = P. x; // The Private member of the P object is accessed here <br/> Y = P. y; // The Private member of the P object is accessed here <br/>}< br/> PRIVATE: <br/> int X, Y; <br/> }; <br/> 

 

Many beginners have misunderstandings about the class permissions.

 

In fact, the class permission is relative to each class,That is, different classes cannot access their private member variables. Different objects of the same class can access their private variables.

 

Someone explained the following:

 

Why can a member function access a private member? Obviously, if the access is unavailable, the existence of private members is meaningless. For data members allowed to access objects in member functions, security and encapsulation are ensured, and convenient operations are also provided. The first sentence is to acknowledge that only member functions can access private members. This does not involve youyuan or derivation. In this way, security is still guaranteed and encapsulation is completed. In the second sentence, imagine if you have to rely on interfaces for data transmission, is the operation extremely inconvenient? Since it is in a member function and ensures sufficient security and encapsulation, it is unreasonable to use the interface here. As a flexible processing of data members, the designer allows users to access private members of objects in member functions, which provides great convenience for users. This also reflects the flexibility and principle of the language.

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.