title: C++ default constructor, initializing pointer with new object
body: <p>I have the following problem:
  In myClass I want to default initialize a pointer to yourClass, with a new yourClass adress.
  Unfortunately, if I want to delete the pointer at any point I get a (core dump).</p>
  
  <pre><code>class myClass
  {
        protected:
        yourClass * yc;
  
        public:
        myClass() { yc = new yourClass(); }
  
        myClass(yourClass * tyc ) { delete yc; yc = tyc; }
  
        ~myClass() { delete yc; yc = NULL; }
  
        void setMyClass (yourClass * tyc) { delete yc; yc = tyc; }
  
        void print () { yc-&gt;print(); }
  };
  
  int main()
  {
    yourClass b (//parameter);
    myClass * a = new myClass();
    a-&gt;print();
    a-&gt;setMyClass(&amp;b)
    a-&gt;print();
  
    delete a;
    return 0;
  }
  </code></pre>
  
  <p>The print() of a, should result in two different prints, dependent on //parameters.</p>
  
  <p>I considered yourClass yc; instead of a yourClass* yc, but I want to know if it is possible.</p>
  
  <p><strong>EDIT:</strong>
  I reworked the code in the following way and it works. Still looks complicated, smart pointers seem promising and I still did not apply the "Rule of Three".
  Here the code. Thanks all.</p>
  
  <pre><code>class myClass
  {
        protected:
        yourClass * yc;
        bool dynamic;
  
        public:
          myClass() { dynamic = true; yc = new yourClass (); }
          myClass (yourClass * tyc ) 
          { 
            // dynamic init (like default)
            if (tyc == NULL ) { dynamic = true; yc = new yourClass (); }
            // static use of yc
            else { dynamic = false; yc = tyc; } 
          }
          // because only if dynamic is true, we need to erase
          ~blu () { if (dynamic) { delete yc; dynamic = false; } } 
  
          void setMyClass(yourClass* tyc) 
          { 
            // leaving unchanged if new-stuff is NULL or like old-stuff
            if ( tyc == yc || tyc == NULL ) return;
            else // treating dynamic and static differently
            { 
              if (dynamic) // if flag is set, must be deleted 
              {
                delete yc; yc = tyc; dynamic = false;
              }
              else // must not be deleted, dynamic is still false
              {
                yc = tyc;
              }
            }
          }
          void print () { yc-&gt;print(); }
  };
  </code></pre>