While looking online at an implementation of vectors for a math engine, i came across this code.
class R4DVector3n{
private:
public:
//x, y and z dimensions
float x;
float y;
float z;
//Constructors
R4DVector3n();
R4DVector3n(float uX,float uY,float uZ);
//Destructors
~R4DVector3n();
//Copy Constructors
R4DVector3n(const R4DVector3n& v);
R4DVector3n& operator=(const R4DVector3n& v);
};
What are the reasons / uses for there being multiple constructors for the class, and furthermore what does the author mean by "copy constructors".
CodePudding user response:
What are the reasons / uses for there being multiple constructors for the class
So that we can create instances of that class using different forms. In other words, to initialize member variables differently for different objects. For example, for your class R4DVector3n we can create instances that uses different constructors depending on the requirements, as shown below:
int main()
{
R4DVector3n obj1; //this creates an object named obj1 of type R4DVector3n using the default constructor
R4DVector3n obj2(1.1f,2.3f, 4.1f); //this creates an object named obj2 of type R4DVector3n using the Parameterized constructor
R4DVector3n obj3 = obj2; //this creates object named obj3 of type R4DVector3n using the copy constructor
}
In the above example, the object obj1 is created using the default constructor.
The object obj2 is created using the parameterized constructor.
The object obj3 is created using the copy constructor.
what does the author mean by "copy constructors".
From copy constructor documentation:
A copy constructor of class T is a non-template constructor whose first parameter is
T&,const T&,volatile T&, orconst volatile T&, and either there are no other parameters, or the rest of the parameters all have default values.
This is useful when we want to create an object using another object. So in your code snippet, you have the following copy constructor:
R4DVector3n(const R4DVector3n& v); //this is a copy constructor
The above statement is a declaration for the copy constructor of class
R4DVector3n. This was used in my example when i wrote:
R4DVector3n obj3 = obj2; //this uses the copy constructor
Also, note that the following statement:
R4DVector3n& operator=(const R4DVector3n& v); //this is copy assignment operator
The above statement is a declaration for the copy assignment operator.
