Unless you declare a copy constructor for your class Figure the language gives you one au gratis, and it's public. You do not want this freebie public copy constructor. It will lead to slicing. Make your copy constructor for class Figure protected. Your copy constructor for the non-abstract derived classes should invoke this protected copy constructor. With this, the clone member function is as simple as new DerivedClass (*this)
:
class Figure {
private:
virtual double varea()=0;
double multiplier;
protected:
Figure () : multiplier(1.0) {}
Figure (const Figure& src) : multiplier(src.multiplier) {}
public:
virtual Figure* clone()=0;
double area() { return varea()*multiplier; }
};
class Square: public Figure {
private:
virtual double varea() {return L*L;}
double L;
public:
Square(const Square & src) : Figure(src), L(src.L) {}
virtual Figure* clone() {return new Square(*this);}
};
Note well:
- I made
Square::varea()
private because that's how it's declared in classFigure
. Exposing a parent class's private method as public in a derived class typically is a bit dubious. - There's an issue with the assignment operator. I'll leave this up to you.
- You need some way to set the
multiplier
.