On 22 Oct 2003 at 19:08, Dave Carrigan wrote:

> On Wed, Oct 22, 2003 at 11:52:00PM +0200, Riccardo Cohen wrote:
> 
> > BUT when not sysAppLaunchFlagNewGlobals, I can't use a class that has a 
> > virtual destructor because it needs global variables. So I removed the 
> > "virtual" keyword from parent and child destructors. I noticed that both
> > destructors are called anyway !
> 
> If the object was created on the stack, then the compiler knows what
> class of object it is and can call the correct destructor when it goes
> out of scope. If the object is allocated from the heap (i.e., with
> operator new), then operator delete will probably call the wrong
> destructor, because the destructor is not declared virtual, so isn't
> in the object's vtable.

I hope I didn't miss understood your answer, but you can still use new/delete 
operation without virtual destructor.  You'll only get into problem when you 
assign the derived class object's pointer to a base class pointer variable and 
then delete the object directly from that base class pointer variable.  I've 
revised my previous example and you run it on other platform that can do "cout" 
to confirm it:

#include <iostream>

using namespace std;

class A
{
        public:
        A() { cout << "Called Class A Constructor\n" << flush; }
        ~A() { cout << "Called Class A Destructor\n" << flush; }
};

class B : public A
{
        public:
        B() { cout << "Called Class B Constructor\n" << flush; }
        ~B() { cout << "Called Class B Destructor\n" << flush; }
};

void main()
{
    cout << "Test 1: Class B destructor will be skipped:\n" << flush;
        A *b1 = new B;
        delete b1;
    cout << "Test 2: Everything is OK:\n" << flush;
        B *b2 = new B;    // Note that we have B* instead of A*
        delete b2;
        cout << "Test 3: Everything is OK as well:\n" << flush;
        B b3;
    cout << "  b3 will be destroyed when main exit.\n" << flush;
}



John Leung
[EMAIL PROTECTED]
http://persweb.direct.ca/jleung


-- 
For information on using the Palm Developer Forums, or to unsubscribe, please see 
http://www.palmos.com/dev/support/forums/

Reply via email to