1: Name masking
Name masking means that the name of the function declared in the subclass is the same as the name of the function declared in the parent class (the return value, parameter type and number are different, and it does not matter if the function is virtual ), subclass objects cannot access functions of the same name defined by the parent class.
Example 1:
# Include <iostream. h> Class B {public: void fun1 () {cout <"B: fun1" <Endl ;}; Class D: Public B {public: void fun1 (INT) {cout <"D: fun1 int" <Endl ;}}; void main () {d; D. fun1 ();}
AboveCodeError returned: Error c2660: 'fun1': function does not take 0 Parameter
The same is true for changing a function to virtual.
2: virtual functions
There are many definitions of virtual functions. Here we will discuss the access to virtual functions.
Example 2:
# Include <iostream. h> Class B {public: void fun1 () {cout <"B: fun1" <Endl ;}; Class D: Public B {public: virtual void fun1 (INT) {cout <"D: fun1 int" <Endl;} virtual void fun1 () {cout <"D :: fun1 "<Endl ;}}; void main () {d; D. fun1 (); B * pb = & D; Pb-> fun1 ();}
Result:
D: fun1
B: fun1
It indicates that the virtual function table is not directly searched in the compiler to determine whether fun1 is in the virtual function table. For me, the compiler will determine which functions of the virtual function table based on the static type (B), and the pointer (PB) can be accessed. In this example, Class B does not have virtual functions, so Pb does not access the virtual function table, and thus does not access fun1 in the virtual function table.
Example 3:
# Include <iostream. h> Class B {PRIVATE: // note the access permission virtual void fun1 () {cout <"B: fun1" <Endl ;}}; Class D: public B {public: Virtual void fun1 (INT) {cout <"D: fun1 int" <Endl;} virtual void fun1 () {cout <"D :: fun1 "<Endl ;}}; void main () {d; D. fun1 (); B * pb = & D; Pb-> fun1 (); // inaccessible}
The access level of Pb-> fun1 () is limited by the static type (B.
Example 4:
# Include <iostream. h> Class B {public: Virtual void fun1 () {cout <"B: fun1" <Endl ;}}; Class D: Public B {PRIVATE: // note the access permission virtual void fun1 (INT) {cout <"D: fun1 int" <Endl;} virtual void fun1 () {cout <"D :: fun1 "<Endl ;}}; void main () {d; // D. fun1 (); B * pb = & D; Pb-> fun1 ();}
Result: D: fun1
The parent class pointer (PB) is used to access the private member of the subclass. The access permission of the description letter is determined by the static type.
The above example is only used for syntax testing, without considering the principles that should be followed by Object-Oriented Design in reality. In case of any errors, let us know.