Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ default constructor, initializing pointer with new object

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(); }
};
like image 813
Alex Avatar asked Feb 01 '13 12:02

Alex


1 Answers

That's because you are trying to delete too much:

  • you are deleting a non-allocated object in the second constructor (remove delete yc;)
  • you are trying to delete a stack-allocated object, b. 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:

  • this post on smart pointers
  • this blog post on RAII
  • any C/C++ primer explaining stack vs. heap allocation (static vs. dynamic?)
like image 130
Lorenzo Dematté Avatar answered Oct 03 '22 17:10

Lorenzo Dematté