class Base
{
public:
Base() { cout << "base constructor" << endl; }
virtual ~Base() { cout << "base destructor" << endl; }
virtual void hello() { cout << "hello Base" << endl; }
};
class Derived : public Base
{
public:
Derived() { cout << "derived constructor" << endl; }
virtual ~Derived() { cout << "derived destructor" << endl; }
virtual void hello() { cout << "hello Derived" << endl; }
};
Derived* d = new Derived();
cout << "-------------------" << endl;
{
static_cast<Base>(*d).hello();
Base b = static_cast<Base>(*d);
b.hello();
}
result
base constructor
derived constructor
-------------------
hello Base
base destructor
hello Base
base destructor
As shown above, dtor is called but ctor is not called. Calling dtor means that a temporary object is created, but why is ctor not called? Is the memory itself copied for optimization? (without the ctor call)