Pure virtual function * * *
When designing an abstract base class, you need to be aware of the following points:
(1) Do not declare destructor as pure virtual function;
If you declare destructor as a pure virtual function, the designer must define it. Because each derived class destructor is extended by the compiler, it calls its "every virtual base class" and "the previous layer base class" destructor in a static invocation.
(2) Do not design a function that does not have a type-related function as a virtual function because it is almost never rewritten by the successor derived class.
(3) A function that may modify a data member for its derived class should not be declared as Const.
Object construction in the case of "no inheritance" * * *
Define class Point first:
class Point {
public:
Point(float x = 0.0, float y = 0.0) : _x(x),_y(y) {}
virtual float z();
protected:
float _x,_y;
};
You can't underestimate the dramatic changes that Z () has brought to class point. The introduction of virtual function prompted each class point to have a vtpr, so that the compiler added code to initialize the Vptr in constructor, and copy constructor and copy The assignment operator also sets the vptr, and is no longer the original bitwise operation.
Please see the following code:
Point foobar()
{
Point local;
Point *heap = new Point;
*heap = local;
delete heap;
return local;
}
will be internally converted to:
Point foobar(Point &_result)
{
Point local;
local.Point::Point();
Point *heap = _new (sizeof(Point));
if(heap != 0)
heap->Point::Point();
*heap = local;
_result.Point::Point(local); // copy constructor的应用
local.Point::~Point();
return;
}
As can be seen from the transformation of the above code: in general, if there are many functions in your design that need to return a local class object in the form of a value (by value), it is more reasonable to provide a copy constructor.
The object construction under the inheritance system * * *
Assuming class Point3D is virtualized to class point, but because class point only has one entity, the constructor of class Point3D needs to be aware of a problem.
Take a look at the following inheritance diagram:
class Point3d : virtual public Point { ... };
class Vertex : virtual public Point { ... };
class Vertex3d : public Point3d, public Vertex { ... };