C + + Language Note Series 12 Inheritance of--c++

Source: Internet
Author: User

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++

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.