Why static_cast make the destructor called

Viewed 111
#include <iostream>

using namespace std;

#define debug(x) cout << #x << ": " << (x) << endl;

class Base {
public:
  void f() { cout << "Base:f()" << endl; }
  ~Base() { cout << "Base:~Base()" << endl; }
};

class A : public Base {
public:
  ~A() { cout << "A:~A()" << endl; }
};

int main() {
  {
    A a;
    static_cast<Base>(a);
  }

  return 0;
}

In this code I call the static_cast to covert the A to Base, the output tells me that it calls the ~Base() twice? why the static_cast make the destructor be called?

1 Answers

static_cast<Base>(a); constructs a temporary Base, which is copied from a. After the full expression the temporary gets destroyed, the destructor of Base is called.

After that, when get out of the scope a gets destroyed, the destructor of A and Base are called in order. Note that this has nothing to do with the static_cast.

Related