Question Regarding Constructor Implementation

chasseml's Avatar, Join Date: Mar 2009
Newbie Member
I have a class that has as a private data member a pointer of the same type.
E.g. The class is "ClassA" and has as a member "ClassA* _classA".

I am writing the copy constructor of ClassA, and would like to do a "deep copy"
of data member _classA, e.g.:

ClassA::ClassA(const ClassA& orig)
: _classA(NULL)
{
if (orig._classA != NULL)
{
_classA = new ClassA(*(orig._classA));
}
}

Is that allowed?

Thanks in advance, chasse
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
_classA = new ClassA(*(orig._classA));

would mean a cyclic reference
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Yes it should be OK. What happens if you try it?
0
asadullah.ansari's Avatar, Join Date: Jan 2008
TechCake
Quote:
Originally Posted by chasseml View Post
I have a class that has as a private data member a pointer of the same type.
E.g. The class is "ClassA" and has as a member "ClassA* _classA".

I am writing the copy constructor of ClassA, and would like to do a "deep copy"
of data member _classA, e.g.:

ClassA::ClassA(const ClassA& orig)
: _classA(NULL)
{
if (orig._classA != NULL)
{
_classA = new ClassA(*(orig._classA));
}
}

Is that allowed?

Thanks in advance, chasse
Why u are calling infinite time means Cyclic . You have do this functionality in some other ways.

If You wanna on stack , your code may be tackle like this

Code:
class ClassA
{
  public:
   void Initialize(ClassA);
   ClassA()
   { 
     cout<<"ctor"<<endl;
   }  
   ClassA(const ClassA &);
   ~ClassA() { cout<<"Dctor"<<endl;}
    void Display() { cout<<"I am here"<<endl;}
  private:
   ClassA*  _classA; 
};

void ClassA :: Initialize(ClassA prev)
{
     _classA = &prev;
 }

ClassA::ClassA(const ClassA& orig)
: _classA(NULL)
{
  cout<<"copy ctor"<<endl;
  if (orig._classA != NULL)
  {
     this->_classA = (orig._classA) ;
   }
}

int main()
{
  ClassA obj1;
  obj1.Initialize(obj1);
  ClassA obj2(obj1);
  //obj2.Display();
  return 0;
}
If You wanna On heap then your code may like this...

Code:
class ClassA
{
  public:
   void Initialize(ClassA*);
   ClassA()
   { 
     cout<<"ctor"<<endl;
   }
  
   ClassA(const ClassA &);
   ~ClassA() { cout<<"Dctor"<<endl;}
    void Display() { cout<<"I am here"<<endl;}
  private:
   ClassA*  _classA;

 
};

void ClassA :: Initialize(ClassA* prev)
{
     _classA = prev->_classA;
 }

ClassA::ClassA(const ClassA& orig)
: _classA(NULL)
{
  cout<<"copy ctor"<<endl;
  if (orig._classA != NULL)
  {
     _classA = new ClassA();
     this->_classA = (orig._classA) ;
   }

}

int main()
{
  ClassA* p1;
  p1 = new ClassA();
  p1->Initialize(p1);
  ClassA obj2(*p1);
  //obj2.Display();
  return 0;
}
This is just an idea . second one itself has hole...Please take care your code and prevent your code from any hole.
Do as your requirement.