简体   繁体   中英

Vtable and *_vptr creation time

The Vtable and *_vptr is created by the compiler at compile-time. When does compiler creates it, before or after the constructor code is executed, or before or after the memory is allocated for the object of the class?

I want to have a clear idea for why virtual constructors is not possible.

The non-existence of virtual constructors has nothing to do with the creation process of the vtable/vptr. In fact, the vtable concept itself is an implementation detail (how/if vtable are used is implementation defined)

Now, what would a virtual constructor do ? The essence of virtual member functions is to provide dynamic polymorphism, when the dynamic type differs from the static type.

But a constructor knows the static type of the object, and it has to be the type of the actual (this) object : there is no dynamic behavior involved here.


Note:

There are design patterns, such as the Virtual Constructor pattern , that allows you to clone an object dynamically, if that's what you are really looking for :

class Shape {
public:
  virtual ~Shape() { }                 // A virtual destructor
  virtual void draw() = 0;             // A pure virtual function
  virtual void move() = 0;
  ...
  virtual Shape* clone()  const = 0;   // Uses the copy constructor
  virtual Shape* create() const = 0;   // Uses the default constructor
};

class Circle : public Shape {
public:
  Circle* clone()  const;   // Covariant Return Types; see below
  Circle* create() const;   // Covariant Return Types; see below
  ...
};

Circle* Circle::clone()  const { return new Circle(*this); }
Circle* Circle::create() const { return new Circle();      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM