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;
}
According to the C++ 17 Standard (12.8 Copying and moving class objects)
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 tonullptr
. This is allowed by the default constructor. In this case the cppy assignment operator can invoke undefined behavior due to this statementAnd 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 *
.