Consider the following (incomplete) class definition: #include #include using namespace std: class ClassA { private: string *ptr;//pointer to a dynamic array of strings: int size: public: ClassA(int n) { ptr = new string[n]: size = n: } ClassA(const ClassA & other): ~ClassA(): ClassA operator = (const ClassA &rhs): Write an implementation of the assignment operator (outside class specification).
Expert Answer
#include <iostream>
#include <string>
using namespace std;
class ClassA
{
private:
string* ptr;
int size;
public:
ClassA(int n)
{
ptr = new string[n];
size = n;
}
ClassA(const ClassA& other);
~ClassA();
ClassA operator=(const ClassA& rhs);
};
// Function implementation for assignment operator
ClassA ClassA::operator=(const ClassA& rhs)
{
ClassA a(rhs.size);
return a;
}
// Destructor
ClassA::~ClassA()
{
}
// copy constructor
ClassA::ClassA(const ClassA& other)
{
ptr = other.ptr;
size = other.size;
}
int main()
{
// Parameterized Constructor
ClassA b(5);
// Copy constructor
ClassA c(b);
// Assignement Operator
ClassA d = c;
return 0;
}