Today, when writing code, I find that the access to the inherited function is not very clear, so I made a test:
1. Header file (test.h) 1 #include <iostream> 2 using namespace std;
3 4 classa{5 Private:6 voidprint () {7cout <<"This is A"<<Endl;8 }9 };Ten One classB: Publica{
};
A is a base class and B is a subclass of a.
2. source Files (test.cpp)
1 " test.h " 2 3 void Main () 4 { 5 New B (); 6 pb->print (); 7 8 GetChar (); 9 GetChar (); Ten }
Because B inherits the function print from Class A and inherits the access rights of print at the same time, the compilation does not pass at this time.
3. Modified header file (test.h)
1#include <iostream>2 using namespacestd;3 4 classa{5 Private:6 voidprint () {7cout <<"This is A"<<Endl;8 }9 };Ten One classB: Publica{ A Public: - voidprint () { -cout <<"This is B"<<Endl; the } -};
Subclass B overrides the print function of a, at which point the compilation succeeds and runs as follows:
4. Summary
When a class inherits from another class, the access permission of the base class member function is the default inherited permission, and if the subclass overrides this function itself, the access permission is changed to the access permission set by the subclass. In short, the function access permissions set by the subclass take precedence over the default access rights of the syntax after inheriting from the base class.
C + + inherited virtual function access rights