title: c++ how to get a pointer to the current object in another class?
body: <p>And again a bad-formulted question, but I don't know how to shortly explain this situation:</p>
  
  <p>I have two classes. Let's name them A and B. A has a lot of member variables and methods. B is a struct which has a shared_pointer to an object of type A. Now A has a method that returns an instance of B (with a pointer to the current instance of A).</p>
  
  <p>My problem is, that A is the subclass of C. C has the same method as described above as pure virtual. The code would look like this:</p>
  
  <pre><code>class C {
  public:
    virtual B mymethod() const =0;
    virtual int getMyvar() const =0;
  };
  
  class A : public C {
  public:
    B mymethod() const override;
    int getMyvar() const override;   //outputs myvar
  private:
    int myvar;
  };
  
  struct B {
    std::shared_ptr&lt;C&gt; pointer;
  };
  
  B A::mymethod() const {
    B instance;
    instance.pointer = std::make_shared&lt;A&gt;(*this);   //is this wrong?
    return instance;
  }
  </code></pre>
  
  <p>My compiler (gcc 4.8.2) creates the executables for the following code, but at runtime I get "Segmentation fault (core dumped)":</p>
  
  <pre><code>void AnotherClass::something() const {
    A object;
    B instance = object.mymethod();
    std::cout &lt;&lt; instance.pointer-&gt;getMyvar();   //dumps the core womehow?
  }
  </code></pre>
  
  <p>I read about the <a href="http://en.cppreference.com/w/cpp/memory/enable_shared_from_this" rel="nofollow">std::enable_shared_from_this</a> but I could not figure out how it works or if it helps me.</p>
  
  <p>Why do I get the error message and how can I fix this?</p>