Constructor/destructor call order

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Rob Steven
    New Member
    • Nov 2010
    • 2

    #1

    Constructor/destructor call order

    Hi,

    The following piece of code
    Code:
    #include <stdio.h>
    
    class A
    {
    public:
        A()
        {
            printf("A constructed\n");
        }
    
        ~A()
        {
            printf("A destroyed\n");
        }
    
        void dummyMethod()
        {
            objectB.methodB(&objectC);
    
        }
    
    private:
        B objectB;
        C objectC;
    };
    
    
    int main(int argc, char *argv[])
    {
        A *ptA = new A;
    
        use(A);
    
        delete A;
    
        return 0;
    }
    outputs this:
    Code:
    B constructed
    A constructed
    ...
    A destroyed
    B destroyed
    *** glibc detected *** ./capture: free(): invalid next size (fast): 0x0000000007fb3090 ***
    ...
    If I comment out the line where methodB is used, I get no B construction/destruction output.
    What I desperately need to know is:
    1) How can B be constructed before A?
    2) Is this the reason behind the glibc error?

    Thanks.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This is not really about constructor/destructor call order.

    Your question really is why are member variable constructors called before the class constructor.

    The sequence is:

    1) the compiler allocates memory for A.
    2) the compiler calls the constructor for each member variable. This is your call to B::B.
    3) once the A object is allocated an all member variables are initialized, then the compiler calls A::A.

    When A is destroyed:

    1) the compiler calls A::~A so that you can clean up any member variables you need to.
    2) the compilers calls the destructor on each member variable. This is your call to B::~B.

    Remember, member variable constructors are called in the order the member variables are declared in the class. The membr variable destructors are called in the reverse order of declaration in the class.

    Finally, you delete the object using the pointer to the object and not the class name:

    delete ptA;

    Comment

    • Rob Steven
      New Member
      • Nov 2010
      • 2

      #3
      Thanks weaknessforcats ! A very clear and helpful answer.

      Comment

      Working...