1. Why should there be abstract classes
For example, the program has two classes, an elliptical ellipse class, and a circle circle class.
We know that ellipses are included in the circle, then we can use inheritance:
class ellipse{}; class circle:public ellipse{};
However, when we define our own member variables and member functions, we find that the members of the two classes are very different,
For example, the Ellipse class needs a short and long axis radius, the center coordinate, the direction angle to determine the position, but also includes moving the ellipse, returning the ellipse area, the method of rotating ellipse.
The Circle class only needs the radius, the center coordinates, can determine the position, the rotation method is also meaningless to the circle.
It can be seen that simple problems are complicated by the simple succession of circle ellipse.
2. What is abstract class
The workaround is that we can abstract out the ellipse class, the public part of the Circle class
classbaseellipse{Private: Doublex; Doubley; Public: Baseellipse (DoubleADoubleb): X (a), Y (b) {}Virtual~baseellipse () {}voidMove (intAintb) {x=a;y=b;} Virtual DoubleArea ()Const=0;//Pure virtual function};
When a class declaration has a pure virtual function, such as virtual double area () = 0, the class is an abstract class.
Abstract classes cannot be instantiated, and when subclasses inherit abstract classes, they must define pure virtual functions.
classEllipse: Publicbaseellipse{ Public: Virtual DoubleArea ()Const{std::cout<<"Ellipse::area ()"<<Std::endl; }};classCircle:publi baseellipse{ Public: Virtual DoubleArea ()Const{std::cout<<"Circle::area ()"<<Std::endl; }};
3. Abstract class and common base class
From the above explanation, it can be seen that the difference between abstract class and ordinary base class is that
the common base class is a parent-child relationship , such as the relationship between a person and a student.
Abstract classes are more like the conventions of an interface rule ,
For example, the provision of some public move () way, for people, the way to move is "go", for birds, is "fly", for the fish, is "swim"
The contract class cannot be instantiated, and all subclasses inheriting from the abstract class must overwrite their pure virtual function, forcing the derived class to follow the interface rules.
Reference: "C + + primer.plus" pp.508-516
C + + abstract class