Basic memo: The derived class directly accesses the Private Members of the base class.

Source: Internet
Author: User
Tags gety

A derived class cannot directly access private members of a base class. to access a base class, you must use the base class interface, that is, its member functions. There are two implementation methods:

1. Add protection members to the declaration of the base class, and define private members provided to the base class for access by the derived class as protection members.

2. Declare the member functions of the derived class that need to access the Private Members of the base class as friends.

# Include <iostream> using namespace STD; class base {friend class derived2; // friend int X; protected: // protected int y;}; Class derived1: base // Private inherits {public:/* int getx () {return X; // invalid. Access the private member of the base class} */INT Gety () {return y; // valid, access the protected member of the base class }}; class derived2: Base // Private inheritance {public: int getx () ;}; int derived2: getx () {return X; // you can directly access the private member of the base class} class derived3: public base // public inheritance {pub LIC:/* int getx () {return X; // It cannot be accessed here, because X is a private member of the base and can only be accessed in the base, it cannot be accessed outside.} */INT Gety () {return y ;}}; int main () {int I; derived2 ob; // The constructor with no parameters or the member function initializes X, the constructor assigns a random value to x I = ob. getx (); cout <I <Endl; derived3 ob3; I = ob3.gety (); cout <I <Endl; System ("pause ");}

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.