Memory allocation of base class and derived class constructor

For which one the space is allocated first when the derived class object is created?

whether base class constructor or derived class constructor?


First,

  • allocation, the reservation of memory which you're asking about, is different from and precedes initialization (execution of a constructor that essentially sets suitable values in that memory), and

  • the formal (our Holy Standard) and the in-practice differ on whether memory for a most derived object needs to be contiguous, with the formal defining a “region of memory” as possibly non-contiguous, mostly in order to support multiple virtual inheritance.

  • That said, in practice a most derived object is a single, contiguous chunk of memory that includes space for all base class sub-objects and data member sub-objects, and this chunk is necessarily allocated all at once.

    Initialization (calls of constructors) proceeds after the allocation. A new expression guarantees a deallocation if initialization fails by throwing an exception. However, this guarantee is voided if the allocation function that's employed has extra custom arguments (a so called “placement new”) and no corresponding deallocation function is available, as was the case eg for debug builds in early versions of Microsoft' MFC class framework (it was pretty ironic: a program where initialization failed would leak memory only in debug builds…).


    The space for the derived object holds all of the derived members and all of the base members. There is only one allocation for the derived object, and the allocated memory holds all the pieces of the object.


    As mentioned in the comment it is the Base class. Logically, since you can access the base public and protected members in the Derived class (including constructor) it will need to be allocated first. Try starting with the following code and play around.

    #include <iostream>
    
    class Base
    {
        public:
        Base() {std::cout<<"Base CTOR" << std::endl;}
    };
    
    class Derived : public Base
    {
        public:
        Derived():Base() {std::cout<<"Derived CTOR"<<std::endl;}
    };
    
    int main(int argc, char* argv[])
    {
        Derived d;
    }
    
    链接地址: http://www.djcxy.com/p/21246.html

    上一篇: IQueryable <T>和IEnumerable <T>有什么区别?

    下一篇: 基类和派生类构造函数的内存分配