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).
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->print(); }
};
int main()
{
  yourClass b (//parameter);
  myClass * a = new myClass();
  a->print();
  a->setMyClass(&b)
  a->print();
  delete a;
  return 0;
}
The print() of a, should result in two different prints, dependent on //parameters.
I considered yourClass yc; instead of a yourClass* yc, but I want to know if it is possible.
EDIT: 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.
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->print(); }
};
                That's because you are trying to delete too much:
delete yc;)delete a; will try to delete a pointer to b, which is an object on the stack; what happens depend on your OS (I expect an exception/core dump/whatever)EDIT: another problem I spotted..
a->setMyClass(NULL)
I would suggest:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With