Protected members of C + + classes Learn notes __c++

Source: Internet
Author: User

When a derived class is publicly inherited from a base class, the member functions of the derived class can directly access the public members of the base class, but they cannot access the private members of the base class. Therefore, in order to facilitate access to derived classes, you can define the members of the base class that need to be provided to the derived class as protection members, and plainly, in a word, derived classes can access members of the protected permission but the objects of the derived class cannot access the members of the base class.

Here is an example:

#include <iostream>

/* Run this program using the console Pauser or add your own getch, System ("pause") or input Loop *
/using namespace std;
Class base{
	//defines a variable for a protected permission for use by derived classes 
	protected:
		int b;
	Public:
		Base (int i) {
			b=i;
		}
		void Print () {
			cout<< "b=" <<b<<endl; 
		}
};

Class Deveried:public base{
	private:
		 int D;
	Public:
		deveried (int i,int j);
		void Print () {
			cout<< "b=" <<b<< "\ T" << "d=" <<d<<endl; 
		}
};	
Here you can initialize the members of the protected permission 
deveried::D everied (int i,int j): Base (i) {
	d = j;
}

int main (int argc, char** argv) {
	Base B (5);
	Deveried d (4,5);
	B.print ();
	D.print ();
	d.b;    Note that this sentence compiles with errors the object of the derived class cannot access the variable of the base class's protected permission, and wants to access return 0 that must be changed to public permission.


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.