Reputation: 519
I receive the following error when I run my test program:
The error goes away if I comment out "delete name," but I can't seem to figure out why. Hopefully someone can give me insight into a solution.
#include<iostream>
#include<string>
using namespace std;
class Shape
{
protected:
string* name = new string;
public:
Shape(string str)
{
*name = str;
}
~Shape()
{
delete name; //Why does my program run if I comment this out?
name = NULL;
}
virtual double getArea() const
{ return 0; }
void setName(string str)
{ *name = str; }
string getName() const
{ return *name; }
};
class Circle : public Shape
{
private:
double radius;
public:
Circle(string str = "", double r = 0) : Shape(str)
{ radius = r; }
void setRadius(double r)
{ radius = r; }
double getRadius() const
{ return radius; }
virtual double getArea() const
{ return radius * radius * 3.14; }
Circle operator= (const Circle &);
Circle operator+ (const Circle &);
};
Circle Circle::operator= (const Circle &right)
{
radius = right.radius;
return *this;
}
Circle Circle::operator+ (const Circle &right)
{
Circle tempCircle;
tempCircle.radius = radius + right.radius;
return tempCircle;
}
int main()
{
Circle c1("c1",5);
Circle c2("c2",10);
Circle c3;
c3 = c2 + c1;
cout << "c1" << c1.getRadius() << endl;
cout << "c2" << c2.getRadius() << endl;
cout << "c3" << c3.getRadius() << endl;
return 0;
}
Upvotes: 0
Views: 87
Reputation: 206737
You are using the compiler defined copy constructor when you use:
c3 = c2 + c1;
That is a problem when you have member data that are allocated from the heap and deallocated in the destructor.
Add proper copy constructors to your classes.
See The Rule of Three for further details.
You can obviate the need for user defined copy constructors and copy assignment operators by changing
string* name = new string;
to
string name;
and changing the rest of your code accordinlgy.
Upvotes: 2