zoukankan      html  css  js  c++  java
  • [转] When exactly does the virtual table pointer (in C++) gets set for an object?

    PS: http://stackoverflow.com/questions/7934540/when-exactly-does-the-virtual-table-pointer-in-c-gets-set-for-an-object

    This is strictly Implementation dependent.

    For Most compilers,

    The compiler initializes this->__vptr within each constructor's Member Initializer list.

    The idea is to cause each object's v-pointer to point at its class's v-table, and the compiler generates the hidden code for this and adds it to the constructor code. Something like:

    Base::Base(...arbitrary params...)
       : __vptr(&Base::__vtable[0])   supplied by the compiler, hidden from the programmer
     {
    
     }

    This C++ FAQ explains a gist of what exactly happens.

    This msdn article explains it in great detali

    There it says :

    "And the final answer is... as you'd expect. It happens in the constructor."

    If I might add, right at the beginning of the constructor, before any other code you might have in your constructor gets executed.


    But be careful, let's say you have the class A, and a class A1 derived from A.

    • If you create a new A object, the vptr will be set right at the beginning of the constructor of the A class
    • But if you create a new object A1:

    "Here's the entire sequence of events when you construct an instance of class A1:

    1. A1::A1 calls A::A
    2. A::A sets vtable to A's vtable
    3. A::A executes and returns
    4. A1::A1 sets vtable to A1's vtable
    5. A1::A1 executes and returns "
  • 相关阅读:
    BZOJ3282 Tree
    [NOI2004] 郁闷的出纳员
    [HNOI2004]宠物收养所
    [HNOI2002] 营业额统计
    图论 简单学习笔记
    POJ3321 Apple tree
    [国家集训队] 聪聪可可
    POJ2976 Dropping tests
    SCOI2005 最大子矩阵
    codeforces|CF13C Sequence
  • 原文地址:https://www.cnblogs.com/qiangxia/p/4710698.html
Copyright © 2011-2022 走看看