On May 24, 8:53 pm, Salt_Peter <pj_h...@yahoo.com> wrote:
On May 24, 10:37 am, Soumen <soume...@gmail.com> wrote:
Hi,
I've following code :
class Base {
public:
virtual void func() { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
void func() { std::cout << "Derived" << std::endl; }
};
class MostDerived : public Derived {
public:
void func() { std::cout << "MostDerived" << std::endl; }
};
int main(int argc, char **argv)
{
Base *pBase = 0;
Derived *pDerived = 0;
try {
pBase = new MostDerived;
pDerived = new MostDerived;
if (pBase) {
pBase->func();
delete pBase;
pBase = 0;
}
if (pDerived) {
pDerived->func();
delete pDerived;
pDerived = 0;
}
} catch (...) {
if (pBase) delete pBase;
if (pDerived) delete pDerived;
}
return 0;
}
On execution, why the o/p is
MostDerived
MostDerived
I's expecting it to be
Derived
Derived
No, its not since you've overridden the virtual function in
MostDerived.
as after Derived, it's no longer virtual ... Please clarify me the
reasons ...
This is incorrect, a virtual function is always virtual. The logic
here is that if you wanted Derived::func() to be called, then don't
override that virtual function in MostDerived or explicitly call
Derived::func() from MostDerived::func().
Thanks ... that means once at least one function in any class is
virtual, any class
derived from it start having a separate _vtable.
Now say func() wasn't virtual in Base. I made it virtual only in
Derived. So I think
there'll not be any Base::_vtable but there'll be Derived::_vtable and
MostDerived::_vtable.
Is my understanding is correct?
By the way, your Base dtor should be virtual (which would also imply
that derivative dtors will also be virtual).
delete pBase; // is a memory leak otherwise.
How could there be leak in this case? Though I admit if Base is
designed to be used as
base class, the dtr should be virtual.
Thanks again to all who clarified it.
Regards,
~ Soumen
The reason for memory leak is non virtual destructor. When you will
in the derived classes will never be deallocated.