Search code examples
c++virtual-destructor

Virtual Destructor: Not Working?


I am using GNU compiler. The Virtual Destructor in class B does not call the Destructor ~D(). Could anyone tell me why?

#include<iostream>
using namespace std;

class B {
  double* pd;
  public:
  B() {
  pd=new double [20];
  cout<< "20 doubles allocated\n";
  }

  virtual ~B() {   //the virtual destructor is not calling ~D()
  delete[] pd;
  cout<<"20 doubles deleted\n";
  }

  };

class D: public B {
  int* pi;
  public:
  D():B() {
  pi= new int [1000];
  cout<< "1000 ints allocated\n";
  }
  ~D() {
  delete[] pi;
  cout< "1000 ints deleted\n";
  }
  };

int main() {
  B* p= new D; //new constructs a D object

Delete should call the virtual destructor in class B but it doesn't.

  delete p; 
  }

Solution

  • It does, you just don't see the output because you've got a typo:

    cout < "1000 ints deleted\n";
    //   ^, less than
    

    Your compiler is being too permissive, this shouldn't compile (at least in C++11).

    It probably does because basic_ios::operator void* makes a stream object implicitly convertible to void* and your compiler is permitting a string literal to decay to char* (which is convertible to void*). cout < "x"; then simply does pointer comparison using built-in operator<(void*, void*) and throws away the result.