Reputation: 22270
I have the following classes:
class Vertex {
public: float X;
float Y;
float Z;
Vertex (float first, float second, float third){
X=first;
Y=second;
Z=third;
}
};
class Obj {
vector<Vertex>vertexCoordinates;
vector<vector<int>> faces;
vector <vector<float>> faceNormals;
vector <vector<float>> faceCenters;
string objName;
int vertexCount, faceCount, edgeCount;
float maxX, minX, maxY, minY, maxZ, minZ, dx, dy, dz;
setVertexCoordinates(vector <Vertex> vertexCoordinatesP) {
vertexCoordinates = vertexCoordinatesP; //??
// How should the assignment be defined?
}
};
Do I need to create a copy constructor here? Overload the operator =
for Vertex
and Obj
?
Upvotes: 5
Views: 396
Reputation: 4921
You should probably use a POD not a class anyhow:
struct Vertex { float x; float y; float z; };
To work around the lack of constructor use factories:
inline Vertex mk_Vertex (float x, float y, float z) {
Vertex a; a.x = x; a.y=y; a.z=z; return a; }
inline Vertex mk_Planar (float x, float y) {
Vertex a; a.x=y; a.y=y; a.z=0.0f; }
This gives you multiple named constructors, and leaves Vertex a POD, which means you can also use C style initialisers:
Vertex a = {1.0f, 2.0r, 3.0f };
which can be quite useful for higher order aggregates such as arrays, or for mapping images on and off disk.
Upvotes: 0
Reputation: 363707
Since your Vertex
has only primitive non-pointer members, you don't necessarily need to define a copy constructor for it: the compiler will generate one for you that copies the elements by their copy constructors (in the case of a float
, that's usually a bitwise copy). The copy constructor and assignment operator for std::vector
are predefined and will work here because you are not storing pointers.
(For an std::vector<Vertex *>
, the ownership semantics would not be clear so you might need to copy in a different way.)
Upvotes: 3
Reputation: 455
You probably don't need to overload these since you don't have any pointers or unsharable references thus the default copy constructor\assignment operator can handle it correctly.
Upvotes: 0
Reputation: 58685
The copy constructor you get free from the compiler will do just fine here. Same goes for the assignment operator you get free of charge or bytes in your source code. The constructor you supplied however eliminates the default constructor the compiler gives, and you need a default constructor for your object to sit in standard containers.
Upvotes: 1