Why is the copy constructor call not called?

I have this code for copying a polygon. The problem is that at the end the vertices point to the original location of the polygon class. Since the copy constructor does not seem to be called. Why is this?

Polygon::Polygon(const Polygon &aPolyToCopy) { int i; vertices = new Vertex[aPolyToCopy.count]; for (i=0;i<aPolyToCopy.count;i++) { vertices[i].x = aPolyToCopy.vertices[i].x; vertices[i].y = aPolyToCopy.vertices[i].y; } count = aPolyToCopy.count; } 

In the list template, I do this

 template <class T, int i> bool SortedVector<T, i>::add ( const T& v ) { myClass[myCurrent] = v; //Copy constructor not called ? myCurrent++; return true; } 

Template

  template <class T, int i> class SortedVector { public: int maxSize; T myClass[i]; int myCurrent; SortedVector(); ~SortedVector(); bool add ( const T& v ); }; 
+4
source share
2 answers

You are assigning , you are not creating a new object here. If you are defining a custom copy constructor, you also need to overload operator =

See http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/ , for example.

If you do something like x = Polygon(y) , then your copy constructor will be called (followed by default operator= ). But don't use this workaround, just specify your operator= .

+3
source

I think the problem in your Polygon class is that you have a vertices data element, which is apparently a raw pointer to Vertex used to store the raw array allocated with new[] :

vertices = new Vertex [aPolyToCopy.count];

You may also need to overload operator= (and the destructor), not just the copy constructor (see Rule of Three ); You did not specify all the code for your Polygon class, so it is unclear whether you have determined the correct assignment and destruction of the copy.

Note that you will simplify your code if you use a robust RAII container container like std::vector . Just add the data element " std::vector<Vertex> vertices; " instead of the data element " Vertex* vertices ", and std::vector will take care of copying, cleaning, etc. You do not need to do anything: all of this is automatically controlled by std::vector .

 #include <vector> // for std::vector class Polygon { std::vector<Vertex> vertices; public: explicit Polygon(size_t vertexCount) : vertices(vertexCount) // Build a polygon with specified vertices {} // // Compiler generated copy constructor, operator= and destructor are fine. // }; 

In general, in C ++, try to assemble classes that bring together convenient RAII structural blocks, such as std::vector and other direct resource managers.

+1
source

All Articles