how to return the result of addition of two objects of a class

133 views Asked by At

On compiling it is showing sme error like use of delete function constexpr Player::Player(const Player&) when it is return the result of addition of the objects.

#include <bits/stdc++.h>

using namespace std;

class Player
{
  char* name;
  int num;

 public:
  Player(char* str = nullptr, int n = -1)
      : name{str}
      , num{n}
  {
    if (str != nullptr)
    {
      name = new char[strlen(str) + 1];
      strcpy(name, str);
      str = nullptr;
    }
  }

  Player& operator=(const Player& temp)
  {
    delete[] this->name;
    this->name = new char[strlen(temp.name) + 1];
    strcpy(this->name, temp.name);
    this->num = temp.num;
  }

  Player operator+(const Player& temp);
};

Player Player::operator+(const Player& temp)

{
  char* str = new char[strlen(name) + strlen(temp.name) + 1];

  strcpy(str, name);
  strcat(str, temp.name);

  int n = num + temp.num;

  Player result{str, n};

  delete[] str;

  return result;
}

int main()

{
  Player p1{"abc", 11};
  Player p2{" xyz", 9};
  Player p3;

  p3 = p1 + p2;
}
1

There are 1 answers

0
Vlad from Moscow On

According to the C++ 17 Standard (12.8 Copying and moving class objects)

7 If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

Also the move constructor is defined as deleted at least because there is explicitly defined the copy assignment operator.

So you need to explicitly define the copy constructor that is required for the operator + to form the return object.

Pay attention to that the class definition has other drawbacks. For example the data member name can be equal to nullptr. This is allowed by the default constructor. In this case the cppy assignment operator can invoke undefined behavior due to this statement

this->name = new char[strlen(temp.name) + 1];
                      ^^^^^^^^^^^^^^^^^

And string literals have types of constant character arrays. So the first parameter of the default constructor shall be declared as having the type const char *.