A pure virtual function is a special virtual function. Its general format is as follows:
Class <Class Name>
{
Virtual <type> <Function Name> (<parameter table>) = 0;
...
};
In many cases, virtual functions cannot be meaningful and implemented in the base class, but it is described as pure virtual functions. Its implementation is left to the derived class of the base class. This is the role of pure virtual functions. The following is an example of a pure virtual function.
# Include
Class Point
{
Public:
Point (INT I = 0, Int J = 0) {x0 = I; Y0 = J ;}
Virtual void set () = 0;
Virtual void draw () = 0;
Protected:
Int x0, y0;
};
Class line: Public point
{
Public:
Line (INT I = 0, Int J = 0, int m = 0, int n = 0): Point (I, j)
{
X1 = m; Y1 = N;
}
Void set () {cout <"line: Set () called. \ n ";}
Void draw () {cout <"line: Draw () called. \ n ";}
Protected:
Int X1, Y1;
};
Class ellipse: Public point
{
Public:
Ellipse (INT I = 0, Int J = 0, int p = 0, int q = 0): Point (I, j)
{
X2 = P; y2 = Q;
}
Void set () {cout <"ellipse: Set () called. \ n ";}
Void draw () {cout <"ellipse: Draw () called. \ n ";}
Protected:
Int X2, Y2;
};
Void drawobj (point * P)
{
P-> draw ();
}
Void setobj (point * P)
{
P-> set ();
}
Void main ()
{
Line * lineobj = new line;
Ellipse * elliobj = new ellipse;
Drawobj (lineobj );
Drawobj (elliobj );
Cout <setobj (lineobj );
Setobj (elliobj );
Cout <"\ nredraw the object... \ n ";
Drawobj (lineobj );
Drawobj (elliobj );
}
Abstract class
Classes with pure virtual functions are called abstract classes. An abstract class is a special class established for the purpose of abstraction and design. It is at the upper layer of the hierarchy of inheritance. Abstract classes cannot define objects. In practice, to emphasize that a class is an abstract class, you can describe the constructor of this class as a protected access control permission.
The main function of an abstract class is to organize the relevant organizations in an inheritance hierarchy to provide them with a public root. The related subclass is derived from this root.
Abstract classes depict the General Semantics of the Operation interfaces of a group of child classes. These semantics are also passed to child classes. In general, an abstract class only describes the operation interfaces of this group of sub-classes, and the complete implementation is left to the sub-classes.
An abstract class can only be used as a base class. The implementation of its pure virtual function is provided by the derived class. If the derived class does not redefine the pure virtual function, and the derived class only inherits the pure virtual function of the base class, the derived class is still an abstract class. If the implementation of the basic class pure virtual function is provided in the derived class, the derived class is no longer an abstract class. It is a concrete class that can create objects.