Re: constructors as virtual
Rahul wrote:
:: Hi Everyone,
::
:: I understand that the constructors can't be virtual and parashift
:: has the following example, to have an workaround for the
:: constructors to be virtual,
::
:: 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(); }
::
:: Now, new Circle() would create a Circle object, and the
:: constructor of bsae class Shape would be called first before
:: Circle right? So how does it offer to be a workaround for the
:: constructors being virtual?
Because if you have a pointer p to an object, p->clone() will get you
another object of the same type, even when you don't know the exact
type.
Bo Persson