Inheritance of C + +
1. How to Inherit
Public (common inheritance)
Members of a derived class can access the public members and protected members of the base class, but not the private members of the base class.
The object of a derived class can only access the public members of the base class.
Protected (protection Inheritance), private (private inheritance)
Members of a derived class can access the public members and protected members of the base class, but not the private members of the base class.
The object of a derived class cannot access any member of the base class.
2. Examples
Example 1:
#include <iostream.h>
Class A
{
Public
void fun1 (int a) {Cout<<a<<endl;}
void fun2 (int b) {Cout<<b<<endl;}
};
Class B:public A
{
Public
void Fun3 () {cout<< "It is in class B." <<endl;}
};
int main ()
{
b b;
A;
B.fun3 (); Y (correct)
B.fun2 (); Y
B.fun1 (); Y
A.fun3 (); N (Error)
A.fun2 (); Y
A.fun1 (); Y
}
Example2:
#include <iostream.h>
Class A
{
Public
void F1 ();
A () {i1 = ten; J1 = 11;}
Protected
int J1;
Private
int i1;
};
Class B:public A
{
Public
void F2 ();
B () {i2 =; J2 = 21;}
Protected
int J2;
Private
int i2;
};
Class C:public B
{
Public
void F3 ();
C () {i3 = +; J3 = 31;}
Protected
int J3;
Private
int i3;
};
The following statement:
(1) member F2 () in derived class B can access the members of Class A F1 () (y), I1 (N), J1 (y).
(2) Derived class object B can access the members of Class A F1 () (Y), I1 (n), J1 (n).
(3) The member function F3 () in the derived class C can access the member F2 () (y), I2 (n), J2 (y) in the direct base class B, and can access the F1 () (y), I1 (n), J1 (y) in the indirect base class A.
(4) Derived class object C can access F2 () (y), I2 (n), J2 (n), and can be interviewed I1 (n), F1 () (y), J1 (n).
Note: Classes have direct access to private, protected, and public members of the class, and the object of the class can only access public in the class directly.
C + + Language Note Series 12 Inheritance of--c++