Busta
Busta

Reputation: 81

C++ initialize list assignment in copy constructor and crashing in copy constructor

I have a situation where I am having trouble redefining a value that was defined in the initialization list. I'd like to redefine this in the copy constructor. I will throw down some sample code. I am also having an issue where my program is crashing once it gets into the for loop of my copy constructor. See anything wild going on there? Doesn't seem to make it out of the for loop without crashing.

in the header file:

class Calculator : public Tool {
private:

    int numberKeys;

    Tool** tools;

public:

    Calculator();
    Calculator(const Calculator& obj);

in the CPP file:

Calculator::Calculator()
:Tool("MyCalculator"),
 numberKeys(0),
 tools(nullptr)
{
}

Calculator::Calculator(const Calculator& obj )
{

numberKeys=obj.numberKeys;
tools = new Tool*[numberKeys];

*****How do I define     :Tool("MyCalculator"),
*****to                  :Tool("YourCalculator"),

for (int x = 0; x < numberKeys; x++){
    this->tools[x] = (obj.tools[i]->clone());

}

}

Upvotes: 0

Views: 134

Answers (1)

Shuba
Shuba

Reputation: 376

If I understand your question correctly, you want the default constructor and copy constructor for Calculator to pass different strings to the parent (base) class.

To do this, use the same assignment list format used for the default constructor. So the definition of the copy constructor will look like:

Calculator::Calculator(const Calculator& obj)
: Tool("YourCalculator"), numberKeys(obj.numberKeys) {
    tools = new Tool*[numberKeys];
    for (int i = 0; i < numberKeys; i++) tools[i] = obj.tools[i]->clone();
}

An extra few coding tips:

  1. When delcaring member variables, I would use m_ or _ prefixes to destinguish from local variables. This way you don't have to keep using this, which can speed up coding in the long run.
  2. Keep an eye on what temp veriables you use in your for loops - you declared int x = 0, and then used obj.tools[i] when i doesn't exist in the local scope.
  3. You can comment code using //, or surround a comment block with /* comment */. ***** will not comment out code.
  4. I would refrain from initializing member variables to nullptr if possible. This may get confusing later on when trying to manipulate them, as it may cause a null-pointer error.

Upvotes: 1

Related Questions