Virtual constructor & covariant return types
Here is a code from
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8
--------------------------------------
class Shape {
public:
virtual ~Shape() { } // A virtual destructor
virtual void draw() = 0; // A pure virtual function
virtual void move() = 0;
...
virtual Shape* clone() const = 0; // Uses the copy constructor
virtual Shape* create() const = 0; // Uses the default constructor
};
class Circle : public Shape {
public:
Circle* clone() const; // Covariant Return Types; see below
Circle* create() const; // Covariant Return Types; see below
...
};
Circle* Circle::clone() const { return new Circle(*this); }
Circle* Circle::create() const { return new Circle(); }
void userCode(Shape& s)
{
Shape* s2 = s.clone();
Shape* s3 = s.create();
...
delete s2; // You need a virtual destructor here
delete s3;
}
--------------------------------------
It seems that behavior of the program will be the same one if we don't
use covariant return types, for instance
class Circle : public Shape {
public:
Shape* clone() const; // Non-Covariant Return Types
Shape* create() const; // Non-Covariant Return Types
...
};
Why do we need covariant return types in the "virtual constructor"
design pattern?
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn