Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ default copy and assignment operator

i have the class

class Circle : public isCircle{
   private :
   int x;
   int y;
   vector<Circle*> _neighbors;
}

where isCircle is just an interface (with virtual methods), and the Circles which _neighbors contains pointers to weren't allocated by this instance. my question is if in this case the default copy and assignment operator would basically do a deep copy ?

like image 460
oopsilon Avatar asked Aug 28 '26 22:08

oopsilon


1 Answers

The default copy constructor for a C++ type works by invoking the copy constructor on each field in the instance with the corresponding field in the object the copy is being created from. In your example it roughly translates to

Circle(const Circle& other) :
  x(other.x),
  y(other.y),
  _neighobrs(other._neighbors) {

}

Whether or not the copy is deep is an implementation detail of each fields' copy constructor. In this case the copy constructor of vector<T> is a bit of a mix. It will deeply copy the underlying storage such that each vector<T> has it's own independent array. However it will copy the elements using the copy constructor. In this case it's a pointer type hence they are copied in a shallow fashion

like image 164
JaredPar Avatar answered Aug 31 '26 14:08

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!