Parent class:
Class cparent
{
....
};
The Declaration of the inheritance class is special:
Class cChild: virtual public cparent
{
....
}
What is the role and meaning of this "virtual?
---------------------------------------------------------------
Virtual inheritance and normal inheritance are two multi-inheritance methods of C ++.
For example, CB1 and CB2 inherit from CA and CC inherit from CB1 and CB2.
If normal inheritance occurs, CC contains two copies of CA, which are from CB1 and CB2.
Virtual Inheritance refers to a copy of a ca.
---------------------------------------------------------------
What is the role and meaning of this "virtual?
This cparent is the virtual base class of cChild.
Role of the virtual base class
The virtual base class refers to: Class subclass: virtual public baseclass
Base Class declared with virtual !! C ++ supports multiple inheritance, so there are several direct parent classes in a derived class, and several direct parent classes may inherit from one base class (that is
Parent class). In this way, when constructing the final derived class, the final derived class contains multiple of the same base classes, this produces a problem of ambiguity (I don't know which base class member variables and functions to call ),
To solve this problem, you need to use the virtual base class, that is, only one memory area is generated for this base class, so that the final derived class will only contain one base class.
Typical scenarios of using a virtual base class are as follows:
A
//
B c
//
D
Where d inherits from BC, and BC inherits from a, so a must be virtualized by BC.
Program ............
Class {
Public:
Void printa () {cout <"This Is A/N ";}
};
Class B: virtual public;
Class C: virtual public;
Class D: Public B, public C;
In this way, after D is constructed, there is only one a in its storage region and there is no ambiguity.
For example: d = new D;
At this time, if D. printa () is used, there will be no problem. However, if B and C do not inherit from a by virtual means, there will be a problem of ambiguity.