0
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)

  • 5
    This will call the copy constructor instead. Try adding `Base(const Base&) {cout<<"Copy-Ctor\n";}` to your class and see the output – nitronoid Aug 09 '18 at 08:50
  • Oh! I was missing a simple thing. Thank you. It was resolved. –  Aug 09 '18 at 08:57
  • 1
    Possible duplicate of [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – Alan Birtles Aug 09 '18 at 10:44

0 Answers0