1. Public inheritance
When a class inherits from a public inheritance, the access properties of the base class's public and protected members are not changed in the derived class, and the private members of the base class are not directly accessible. ---that is, the public and protected members of the base class are inherited to the access property in the derived class, still as the public and protected members of the derived class, and other members of the derived class can access them directly. A public member inherited from a base class can be accessed only by an object of the derived class outside the class family, and neither the member of the derived class nor the object of the derived class can access the private members of the base class directly.
eg
The point class is public-inherited.
In this example, a new rectangle (Rectangle) class is derived from the point class. A rectangle is made up of a point with a length and width, a rectangular point that has all the features of the points class, and a rectangle that has its own characteristics, which requires the addition of a new member while inheriting the Dot class.
The header file portion of the program
Rectangle.h
Definition of Class point//Base class Point
{
Public
void Initp (float xx=0,float yy=0) {x=xx; Y=yy;}
void Move (float xoff,float yoff) {x+=xoff; Y+=yoff;}
Float GetX () {return X;}
Float GetY () {return Y;}
Private
float x, y;
};
Class Rectangle:public Point//derived class definition section
{
Public://new Members
void Initr (float x,float y,float w,float h)
{INITP (x, y); W=w; H=h;} Call the base class public member function
Float Geth () {return H;}
Float GETW () {return W;}
Private://new Proprietary data member
float w,h;
};
End of Rectangle.h
The base class point is defined first, and the derived class rectangle inherits all the members of the Point class
Because the inheritance is public, the public members of the base class are kept intact in the derived class, and the member function set objects of the derived class can access the public members of the base class. The original outer interface of the base class becomes part of the external interface of the derived class. Of course, the new members of the derived class have access to each other.
Here is the main function part of the program
#include <iostream>
#include <cmath>
#include "rectangle.h"
using namespace Std;
int main ()
{
Rectangle rect;//declaring objects of the Rectangle class
Rect. Initr (2,3,20,10);//Set the data for the rectangle
Rect. Move (3,2);//moving the rectangle position
cout<< "The Data of Rect (X,Y,W,H):" <<endl;
Cout<<rect. GetX () << ","
<<rect. GetY () << ","
<<rect. GETW () << ","
<<rect. Geth () <<endl;
}
2. Private inheritance
5. Inheritance and derivation 2-access control