Virtual constructor & virtual copy constructor

virtual constructor :  virtual constructor is function that creates different type of object of objects depending on the input it is given.

Example: Factory design pattern is the example of virtual constructor.

virtual copy constructor :
virtual copy constructor returns a pointer to a new copy of the the object invoking the function. Because of this behaviour, virtual copy constructor is also known as 'copyself', 'cloneself' or just 'clone'.

class base {
    public:
        virtual base* clone() = 0;
};

class Text : public base
{
    public:
        virtual Text* clone()
        {
            return new Text(*this);
        }
};

class Image : public base
{
    public:
        virtual Image* clone()
        {
            return new Image(*this);
        }
};

If real copy constructor perform swallow copy, then virtual copy constructor also perform swallow copy. If real copy constructor perform deep copy then virtual copy constructor perform deep copy.

Comments

Popular posts from this blog

IPC (Inter-Process Communication) on Linux

Difference between new and malloc

Vitrual Function Implementation