Very short inheritance question

J

james

the only thing you need is vritual function, please look at my replyed post
at "clarification - calling virtual function from destructor"
james
 
S

Skirmish

I am deriving B from A. Is it possible to have both A and B's
destructor called by calling Release in the base object?

#include <stdio.h>

//-------------Base Object-------------//
class A
{
public:
A(void) {}
~A(void) {printf("A is deleted\n");}
void Release(void) {delete this;}
};
//-------------------------------------//

//------------Child Object-------------//
class B : public A
{
public:
B(void) {}
~B(void) {printf("B is deleted\n");}
};
//-------------------------------------//

void main(int argc, char **argv)
{
B *b = new B();
b->Release();
getchar(); //keep console open
}

//OUTPUT: A is deleted

BTW this code is a simmered down version of memory managed object.
Cheers
-A-
 
S

Sharad Kala

Skirmish said:
I am deriving B from A. Is it possible to have both A and B's
destructor called by calling Release in the base object?

#include <stdio.h>

//-------------Base Object-------------//
class A
{
public:
A(void) {}
~A(void) {printf("A is deleted\n");}
void Release(void) {delete this;}
};
//-------------------------------------//

//------------Child Object-------------//
class B : public A
{
public:
B(void) {}
~B(void) {printf("B is deleted\n");}
};
//-------------------------------------//

void main(int argc, char **argv)
{
B *b = new B();
b->Release();
getchar(); //keep console open
}
Yes. Change the destructor in your base class to be virtual.
virtual ~A(void) {printf("A is deleted\n");}
Call the release member function through a polymorphic pointer in main.

A* b= new B();
b->Release();

btw, your code should be using cout and not printf's.
Getting pedantic, main has never ever returned void so return int.

-Sharad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top