"sam" <sa********@yahoo.comwrote in message
news:11**********************@a75g2000cwd.googlegr oups.com...
Hi,
See when i reading a sourcecode of a program,
I read that the constructor is ordinary and after that the programmer
has written virtual destructor for that constructor .
Why we use the virtual destructor whats the use of it?
the code is like this:
Network(int input,int output);
Network(&Network);
virtual ~Network();
My question is why he use virtual destructor.
If you derive from a base class and don't have a virtual destructor, there
are times when the derived classe's destructor won't be called.
Case in point, output from this program is:
Base1 Destructor
Derived2 Destructor
Base2 Destructor
We are missing a Derived2 Destructor
#include <iostream>
#include <string>
class Base1
{
public:
~Base1() { std::cout << "Base1 Destructor\n"; }
};
class Derived1: public Base1
{
public:
~Derived1() { std::cout << "Derived1 Destructor\n"; }
};
class Base2
{
public:
virtual ~Base2() { std::cout << "Base2 Destructor\n"; }
};
class Derived2 : public Base2
{
public:
~Derived2() { std::cout << "Derived2 Destructor\n"; }
};
int main ()
{
Base1* Foo = new Derived1;
Base2* Bar = new Derived2;
// delete Foo does not cause Derived1's destructor
// to be called, because Base1's destructor is not virtual
delete Foo;
delete Bar;
std::string wait;
std::getline( std::cin, wait );
}