This is my class:
(I know currently it violates the rule of three because it doesn't yet have an explicitly defined copy assignment operator.)
#include <iostream>
template <class T>
class die
{
private:
int sideCount;
T* valueOfSides;
public:
die() : sideCount(0), valueOfSides(nullptr) {}
die(int sideCount, T* valueOfSides) : sideCount(sideCount), valueOfSides(nullptr)
{
this->valueOfSides = new T[sideCount];
for (int i = 0; i < sideCount; ++i)
this->valueOfSides[i] = valueOfSides[i];
}
die(const die& that) : sideCount(that.sideCount), valueOfSides(nullptr) //<- WARNING
{
valueOfSides = new T[sideCount];
for (int i = 0; i < sideCount; ++i)
valueOfSides[i] = that.valueOfSides[i];
}
void printValueOfSides() //Unrelated but I will leave this method here if you decide to use it
{
for (int i = 0; i < sideCount; ++i)
std::cout << "valuesOfSides[" << i << "] = " << valueOfSides[i] << std::endl;
}
~die() { delete[] valueOfSides; }
};
The warning at the copy constructor's initializer list is:
die(const die& that) : sideCount(that.sideCount), valueOfSides(nullptr)<-here
The value (I'm guessing nullptr
) is never used. When I remove valueOfSides(nullptr)
from the copy constructor's initializer list the warning goes away. I know code works without it but for the sake of completion when a die object is created using the copy constructor
int main()
{
die<int> d1(4, array);
die<int> d2(d1);
return 0;
}
I want it first to be initialized with the nullptr
then assigned to the values in the constructor's parameter. As its being done with the parameterized constructor.
So my questions are:
- Why do I get this warning In the copy constructor but not In the parameterized constructor?
- I include
valueOfSides
pointer in the member initializer of all the constructors for the sake of completion and because I believe it is good practice to initialize the members even though they will get assigned in the body of the constructor. Is this a good practice or a habit? Or should I just give up InitializingvaluesOfSides
when it is not necessary to initialize? In this case, only include it in the member initializer of the default constructor and not in the parameterized and copy constructor? - For my second question, Am I accurate with my depictions of initialization and assignment of members?
Aucun commentaire:
Enregistrer un commentaire