CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Join Date
    Mar 2009
    Location
    Cambodia
    Posts
    16

    why Destructor of base class is called twice?

    Hello guru,

    I encounter a strange an unfamiliar situation while trying to test out class inheritance and contructor overloading. I write the code below for testing purpose only:

    class A{
    A(){cout<<endl<<"A initiating...";}
    ~A(){cout<<endl<<A ending...";}
    };

    class B:public A{
    B(){cout<<endl<<"B initiating...";}
    ~B(){cout<<endl<<B ending...";}
    };


    void myFunction(A a){

    }

    int main(){
    B b;

    cout<<endl<<"Call function";

    myFunction(b);

    getchar();
    return 0;
    }

    -------------------------Output-----------------------

    B initiating...
    A initiating...

    Call function

    A ending...
    A ending...

    --------------End output---------------

    My question is why the destructor of Class A is called 2 times?


    Thanks,
    Last edited by Brad Jones; March 17th, 2009 at 02:23 PM.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: why Destructor of base class is called twice?

    Since you passed by value into the function, all you had in the fuction was a local A. All of its B-ness was sliced off. When the function returns, the local A is destroyed.

    The reason you don't see a corresponding "A initiating..." print is because that parameter was created with the default copy constructor rather than the normal constructor you defined.

    Typically when using inheritance you want to be passing either by reference or using a pointer, not by value.

  3. #3
    Join Date
    Mar 2009
    Location
    Cambodia
    Posts
    16

    Re: why Destructor of base class is called twice?

    I get your point,

    because my function expects class A as argument, then i will convert my parameter from Class B to A. And I do understand that because of copy constructor is used, no constructor function is called for the local class A.

    Once the function returns, it will call the destructor of class A. what i don't understand is why does the function calls the destructor of class A 2 times instead of 1 time.

    Can you explain this?


    Thanks,

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: why Destructor of base class is called twice?

    Quote Originally Posted by piggy181
    Once the function returns, it will call the destructor of class A. what i don't understand is why does the function calls the destructor of class A 2 times instead of 1 time.
    Yes, once myFunction() returns, the destructor of A will be invoked. Then, once main() returns, the destructor of B will be invoked, and this will invoke the destructor of A. One, two!
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  5. #5
    Join Date
    Mar 2009
    Location
    Cambodia
    Posts
    16

    Re: why Destructor of base class is called twice?

    No, you should run the code in VS 2008 and see the result for your self. The destructor of class A is called 3 times if you include the one called when function main exit.

    Look back at my code, i have a getchar() function call before the main function returns. so when i run the program, while the command prompt is waiting for a key press, there are already 2 "A ending..." displayed, which means class A destructor is called 2 times.

  6. #6
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: why Destructor of base class is called twice?

    Quote Originally Posted by piggy181
    No, you should run the code in VS 2008 and see the result for your self. The destructor of class A is called 3 times if you include the one called when function main exit.
    I do not have MSVC9 (VS 2008), but both MSVC8 (VS 2005) and the MinGW port of g++ 3.4.5 give me this output:
    Code:
    A default ctor
    B default ctor
    Call function
    A copy ctor
    A dtor
    B dtor
    A dtor
    for this program:
    Code:
    #include <iostream>
    
    using namespace std;
    
    class A
    {
    public:
        A() { cout << "A default ctor" << endl; }
    
        A(const A&) { cout << "A copy ctor" << endl; }
    
        A& operator=(const A&)
        {
            cout << "A copy assignment operator" << endl;
            return *this;
        }
    
        ~A() { cout << "A dtor" << endl; }
    };
    
    class B : public A
    {
    public:
        B() { cout << "B default ctor" << endl; }
    
        B(const B&) { cout << "B copy ctor" << endl; }
    
        B& operator=(const B&)
        {
            cout << "B copy assignment operator" << endl;
            return *this;
        }
    
        ~B() { cout << "B dtor" << endl; }
    };
    
    void myFunction(A a) {}
    
    int main()
    {
        B b;
        cout << "Call function" << endl;
        myFunction(b);
    }
    The output can differ, especially for cases where the compiler can elide the copy constructor and perform other optimisations, but the point is that the number of constructor invocations will match the number of destructor invocations. If you find a mismatch, then you are not tracking them properly.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  7. #7
    Join Date
    Mar 2009
    Location
    Cambodia
    Posts
    16

    Re: why Destructor of base class is called twice?

    You're right, with copy constructor implemented in class A, the number of constructor plus copy constructor will match the number of destructor.

    But you haven't answered my question yet: without the copy constructor implemented, class A destructor is called twice when "myFunction" return.

    I do understand that the compiler will provide a default copy constructor when one is not found. i don't have any doubt about that. but wonder why the destructor function get called twice. does the compiler create 2 instance of local class A object when "myFunction" is called.

    Please comment.

    Thanks,

  8. #8
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    Re: why Destructor of base class is called twice?

    You said
    I do understand that the compiler will provide a default copy constructor when one is not found. i don't have any doubt about that. but wonder why the destructor function get called twice. does the compiler create 2 instance of local class A object when "myFunction" is called.
    and still don't understand? Copy constructor is still a constructor. No mater what constructor is called, an object is created. Take another look at laser's output:
    A default ctor
    B default ctor
    Call function
    A copy ctor
    A dtor
    B dtor
    A dtor
    You can see that the number of constructor calls and destructors is the same. It's always the same.
    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

  9. #9
    Join Date
    Mar 2009
    Location
    Cambodia
    Posts
    16

    Re: why Destructor of base class is called twice?

    //Copy this code to compile and run, you will get a better idea of what i mean:

    ---------------------------


    #include <iostream>

    using namespace std;

    class A{
    public:
    A(){cout<<"A initiating..."<<endl;}
    //A(const A&) { cout <<"A copy ctor" << endl; }
    ~A(){cout<<"A ending..."<<endl;}
    };

    class Bublic A{
    public:
    B(){cout<<"B initiating..."<<endl;}
    ~B(){cout<<"B ending..."<<endl;}
    };

    class Cublic B{
    public:
    C(){cout<<"C initiating..."<<endl;}
    ~C(){cout<<"C ending..."<<endl;}
    };

    void myFunction(A a){

    }

    void callMyFunction(){
    C c;
    myFunction(c);
    }

    int main(){
    cout<<"Call function"<<endl;
    callMyFunction();
    cout<<"after function call"<<endl;

    getchar();
    return 0;
    }

  10. #10
    Join Date
    Apr 1999
    Posts
    27,449

    Re: why Destructor of base class is called twice?

    Quote Originally Posted by piggy181 View Post
    //Copy this code to compile and run, you will get a better idea of what i mean:
    Please use code tags and remove the smilies from your post. The message window will have these options.

    Regards,

    Paul McKenzie

  11. #11
    Join Date
    Apr 1999
    Posts
    27,449

    Re: why Destructor of base class is called twice?

    Quote Originally Posted by piggy181 View Post
    //Copy this code to compile and run, you will get a better idea of what i mean:
    You still commented out the copy constructor for A. The destructor for the copy is being called, but you never know where that destructor call comes from because you commented out the copy constructor.

    Take out that comment and run the program.

    Regards,

    Paul McKenzie

  12. #12
    Join Date
    Mar 2009
    Location
    Cambodia
    Posts
    16

    Re: why Destructor of base class is called twice?

    ------------------------------
    You still commented out the copy constructor for A. The destructor for the copy is being called, but you never know where that destructor call comes from because you commented out the copy constructor.


    Actually i commented out the copy constructor on purpose. and that's the point i want to ask. with the copy constructor in place, the number of constructor and destructor is the same.

    without the copy constructor, the number of destructor is 2 more than that of the constructor. there should only be 1, but why 2?


    Can you explain?

  13. #13
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    Re: why Destructor of base class is called twice?

    My head aches. Don't you understand that the number of calls to constructors and destructors is always the same? Each object is created EXACTLY ONCE and destructed EXACTLY ONCE. You have N objects of type T, you have N calls to constructors (could be more for type T) and N calls to the destructor (only one for each type).
    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

  14. #14
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: why Destructor of base class is called twice?

    Quote Originally Posted by piggy181
    without the copy constructor, the number of destructor is 2 more than that of the constructor. there should only be 1, but why 2?
    As you yourself have stated, without the user defined copy constructor, the compiler provides it since copy construction occurs. So, the copy constructor is still there, except that it is not being tracked.

    Let me put it another way:
    Code:
    #include <iostream>
    
    using namespace std;
    
    class A
    {
    public:
        ~A() { cout << "A dtor" << endl; }
    };
    
    int main()
    {
        A a;
    }
    I get the output:
    Code:
    A dtor
    But this does not make sense! I have not constructed any A objects, so why is the destructor for A invoked?

    Do you see that my faulty reasoning is akin to your own reasoning concerning the "extra" destructor invocation?
    Last edited by laserlight; March 17th, 2009 at 06:56 AM.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  15. #15
    Join Date
    Mar 2009
    Location
    Cambodia
    Posts
    16

    Re: why Destructor of base class is called twice?

    --------------------------
    As you yourself have stated, without the user defined copy constructor, the compiler provides it since copy construction occurs. So, the copy constructor is still there, except that it is not being tracked.
    --------------------------

    Thanks for your comment,

    The above statement is right, and i wouldn't have anymore doubt if my code produce just one extra destructor, because it's corresponding copy constructor is provided by the compiler, so it's hidden.

    My curiosity is why my program produces 2 extra destructor. So my question is where does the second destructor come from?

    It may take much of your time and i guess it's boring for u, i just want to clear out my doubt and to make sure u understand what my question.

    Thanks,

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured