Question Overload the and operators for the square class w
Question:
Overload the + and = operators for the square class we have provided you.
The = should make a deep copy of the square object.
The + operator should concatenate the names of the two squares and add their lengths.
Explain why we should be overloading the assignment operator in a comment.
given code:
//main.cpp
#include <iostream>
#include <string>
using namespace std;
int main(){
Square a;
Square b = a;
Square c(a);
return 0;
}
//square.cpp
#include <iostream>
#include <string>
using namespace std;
#include \"square.h\"
Square::Square() {
name = \"mysquare\";
lengthptr = new double;
*lengthptr = 2.0;
}
void Square::setName(string newName) {
name = newName;
}
void Square::setLength(double newVal) {
*lengthptr = newVal;
}
string Square::getName() const {
return name;
}
double Square::getLength() const {
return *lengthptr;
}
Square::Square(const Square & other) {
cout << \"I am copying!\" << endl;
name = other.getName();
lengthptr = new double;
*lengthptr = other.getLength();
}
Square::~Square() {
delete lengthptr;
}
//square.h
#ifndef _SQUARE_H
#define _SQUARE_H
class Square {
private:
string name;
double * lengthptr;
public:
Square();
Square(const Square & old);
~Square();
void setName(string newName);
void setLength(double newVal);
string getName() const;
double getLength() const;
};
#endif
//Makefile
EXENAME = main
CXX = clang++
CXXFLAGS = -std=c++0x -g -O0 -Wall -Wextra
all : $(EXENAME)
$(EXENAME): main.cpp square.cpp square.h
$(CXX) $(CXXFLAGS) main.cpp square.cpp -o $(EXENAME)
.PHONY: clean
clean:
rm -f $(EXENAME)
Solution
//Put this code in square.cpp file
//Overloading + operator
Square Square::operator+(const Square& square)
{
//Creating a new square object for representing the result
Square result = new Square();
string newName;
//Concatenating both names and storing the result in \"result\" object\'s name
strcat(newName, name);
strcat(newName, square.getName());
result.setName(newName);
//Adding both lengths and storing in result object
double newLength = 0;
newLength = square.getLength() + *lengthptr;
result.setLength(newLength);
return result;
}
//Overloading the = operator
//Reason why we have to overload the assignment operator
//The default assignment operator performs a bit pattern copy i.e.
//simply copies data members of one object into another object.
//It works fine, until class member isn\'t allocated any resource(file or memory)
//Hence it performs a shallow copy by default (i.e copying data members irrespective of their type)
//To perform deep copy(i.e pointers must not be copied,
//instead there should be separate memory allocation for them)
//we need to overload the assignment operator and create a custom copy constructor for the class
void Square::operator=(const Square& square)
{
name = square.getName();
*lengthptr = square.getLength();
}


