title: Converting this to shared pointer and passing it as an argument to another C++ class
body: <p>I am working on a code with the following framework:</p>
  
  <pre><code>class IFirstStep // abstract interface
  {
  public:
      virtual commonMethod1() = 0;
      ...
  };
  
  class FirstStepBase : public IFirstStep // Jobs common to all FirstStep's
  {
  public:
      FirstStepBase() {}
      commonMethod1() override;
      ...
  protected:
      CommonMembers;
      void correctSettings()
      {
          somePreparations;
          auto smartPtr = static_cast&lt;std::shared_ptr&lt;IFirstStep&gt;&gt;(this);
          SecondStep secondStep(smartPtr);
          some calculations using secondStep;
          reassignment of some of commonMembers;
      }
  };
  
  class FirstStep1 : public FirstStepBase
  {
  public:
      FirstSiep1(bool fineTune)
      {
          commonMembers = initilizeSettings();
          if (fineTune)
              correctSettings();
      }
  private:
      CommonMembers initilizeSettings() {calculate and assign commonMembers;}
  };
  
  class FirstStep2 : public FirstStepBase
  ...
  class FirstStepN : public FirstStepBase
  ...
  
  class SecondStep
  {
  public:
      SecondStep(std::shared_ptr&lt;IFirstStep&gt; &amp; firstStep) : m_firstStep(firstStep) {}
      some methods which use firstStep and return some results;
      firstStep itself is not changed;
  };
  </code></pre>
  
  <p>correctSettings() is perfectly executed correcting all settings for FirstStep1 right, but crashes in MS VS debugger on exit from correctSettings() with the diagnostics:</p>
  
  <pre><code>File: minkernel\crts\ucrt\src\appcrt\heap\debug_heap.cpp
  Line: 888
  Expression: _CrtIsValidHeapPointer(block)
  </code></pre>
  
  <p>Looks the problem is caused by casting - code crashes even if exit is carried out just after the casting. Other types of casting, including pointer casts, were not accepted by the MS VS compiler. However, the thing works flawlessly if correctSettings() is changed as follows and an appropriate constructor is added to FirstStepBase</p>
  
  <pre><code>void correctSettings()
  {
      std::shared_ptr&lt;IFirstStep&gt; smartPtr 
          = &lt;std::make_shared&lt;FirstStepBase&gt;&gt;(commonMembers);
      SecondStep secondStep(smartPtr);
      some calculations using secondStep;
      reassignment of some of commonMembers;
  }
  </code></pre>
  
  <p>I would greatly appreciate an explanation of why the first approach fails and is it possible at all to utilize in the code this pointer rather than to generate an additional FirstStepBase object? Please, assume that there is no possibility to change interface to the SecondStep.
  Thank you.</p>