Why and when should use a Copy Constructor in C++?

Lets say we create an object of class Student, we create two instances/objects class Student(i.e. StudentA and StudentB). We do shallow copy to initialize data members of B with that of A as follows:

Student StudentB = StudentA;

And then we destroy StudentB. Are we facing a situation of Dangling Pointer here? Why and how? Please explain.

‚úÖ Answers

ūü•á Favorite Answer

  • It would happen if one of the data members of class Student was an std::auto_ptr, because copying of auto pointers (unlike shared pointers) transfers ownership from StudentA to StudentB, and destruction of StudentB deletes the pointed-to object, leaving StudentA with a pointer to non-existing object.

    Likewise if one of the members was a raw pointer and if the destructor of Student calls delete on it, but who uses raw pointers in C++ anymore? It’s like using goto in C.

    Chris C: he said “shallow copy”

  • Whenever code readability is a requirement. Which should be always.

    There won’t be a dangling pointer, as long as the local variables that are defined in the class are an actual copy instead of a copy of the pointer.

    An example of this would be:

    class MyClass

    {

    public:

       MyClass()

       {

          aString = calloc(, sizeof(char));

       };

       ~MyClass()

       {

          if (aString)

             free(aString);

       };

       

       operator =(const MyClass &rightSide)

       {

          if (this->aString == NULL)

          {

             this->aString = calloc(, sizeof(char));

             strcpy(this->aString, rightSide->aString);

          }

       };

       /*

          Do NOT do this:

       operator =(const MyClass &rightSide)

       {

          this->aString = rightSide->aString;

       };

       */

    protected:

       char *aString;

    };

  • See also  Interfacing with a new bluetooth device unknown API C#?

    Leave a Comment