"Calvin Lai" <> wrote in message
news

A3Eb.72661$ ble.rogers.com...
> Hi all,
>
> I have a simple question. If I have a ClassA as base class, and ClassB
> derive from it. There is a virtual function foo() in ClassA, and in Class
B,
> I defined a function called foo() as well (w/ or w/o declaring it as
virtual
> doesn't matter since the virtual is inhered, right?).
Correct.
> Both of them have a
> virtual destructor.
>
> Now, here is the part of the code:
>
> ClassA::foo()
> {
> cout << "In class A"
> }
>
> ClassB::foo()
> {
> cout << "In class B"
> }
>
> ClassA::~ClassA()
> {
> cout << "destroying A"
> }
>
> ClassB::~ClassB()
> {
> cout << "destroying A"
> }
>
> When deleting objectB (from ClassB), both destructors are called. However,
> when calling objectB's foo, only the classB's foo is called. Why is that?
Because an object of type ClassB is actually composed of parts of both
ClassA and ClassB. Let's say in ClassA there were a file, and in ClassB
there was also a file. In an object of type ClassA, there will be 1 file.
In an object of type ClassB, there will be 2 files. When you delete an
object of ClassB, don't you want to make sure that both files are closed?
The closing of the file in ClassA should logically be closed in the
destructor for ClassA. On the other hand, functions aren't the same as
storage. Functions have to do with behavior, and if you want the behavior
of ClassB to be different from that of ClassA, then there's no reason to
call ClassA's function. You could though. In ClassB::foo(), you could make
a call to ClassA::foo(). Then it would work the same way as the destructor
calls.