Destructors of Derived classes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mike

    Destructors of Derived classes

    I seem to be having a problem with the way destructors are called with
    derived classes. Below is a short example of what I'm trying to do.
    In the example a is the base class. It has a function 'action' which
    destroys the object. As I understand derived classes and destructors,
    the destructor of the derived class should be called first, then the
    destructor of the base class. Really, for my purposes, order doesn't
    matter. In my example here I would only get the output "a:~a". It
    never executes the destructor of the derived class.

    The code below is just an example to simply show an idea, it hasn't
    been compiled.


    class a
    {
    public:
    action();
    ~a();

    };

    class a_derivative:a
    {
    public:
    ~a_derivative() ;

    };


    a:~a()
    {
    printf("a:~a");
    }

    a:action()
    {
    delete this;
    }


    a_derivative:~a _derivative()
    {
    printf("a_deriv ative:~a_deriva tive");
    }


    main()
    {
    a_derivative* my_a;

    my_a = new a_derivative();

    my_a->action();

    }
  • Alf P. Steinbach

    #2
    Re: Destructors of Derived classes

    On 30 Jul 2003 08:44:36 -0700, hageland@yahoo. com (Mike) wrote:
    [color=blue]
    >I seem to be having a problem with the way destructors are called with
    >derived classes. Below is a short example of what I'm trying to do.
    >In the example a is the base class. It has a function 'action' which
    >destroys the object. As I understand derived classes and destructors,
    >the destructor of the derived class should be called first, then the
    >destructor of the base class. Really, for my purposes, order doesn't
    >matter. In my example here I would only get the output "a:~a". It
    >never executes the destructor of the derived class.
    >
    >The code below is just an example to simply show an idea, it hasn't
    >been compiled.
    >
    >
    >class a
    >{
    > public:
    > action();[/color]

    void action();


    [color=blue]
    > ~a();[/color]

    virtual ~a();



    [color=blue]
    >
    >};
    >
    >class a_derivative:a
    >{
    > public:
    > ~a_derivative() ;
    >
    >};
    >
    >
    >a:~a()
    >{
    > printf("a:~a");
    >}
    >
    >a:action()
    >{
    > delete this;
    >}
    >
    >
    >a_derivative:~ a_derivative()
    >{
    > printf("a_deriv ative:~a_deriva tive");
    >}
    >
    >
    >main()[/color]

    int main()


    [color=blue]
    >{
    > a_derivative* my_a;
    >
    > my_a = new a_derivative();
    >
    > my_a->action();
    >
    >}[/color]

    Comment

    Working...