Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning C++ class with pure virtual methods

Tags:

c++

virtual

I have the following relation of classes. I want to clone the class Derived, but I get the error "cannot instantiate abstract class". How I can clone the derived class? Thanks.

class Base {
public:
    virtual ~Base() {}
    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual void func() = 0;
    virtual Derived* clone() const {
        return new Derived(*this);
    }
};
like image 577
Joan Carles Avatar asked May 14 '12 15:05

Joan Carles


3 Answers

Only concrete classes can be instantiated. You have to redesign the interface of Derived in order to do cloning. At first, remove virtual void func() = 0; Then you will be able to write this code:

class Base {
public:
    virtual ~Base() {}
    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual Derived* clone() const {
        return new Derived(*this);
    }
};

Another solution is keeping pure virtual function in-place and adding a concrete class:

class Base {
public:
    virtual ~Base() {}
    virtual Base* clone() const = 0;
};

class Derived: public Base {
public:
    virtual void func() = 0;
};

class Derived2: public Derived {
public:
    virtual void func() {};
    virtual Derived2* clone() const {
        return new Derived2(*this);
    }
};
like image 190
Sergey K. Avatar answered Nov 15 '22 03:11

Sergey K.


You can not instantiate a class which has a pure virtual function like this:

virtual void yourFunction() = 0

Make a subclass or remove it.

like image 28
Martol1ni Avatar answered Nov 15 '22 01:11

Martol1ni


Only concrete class can be instancied. Func should be not pure.

like image 2
VGE Avatar answered Nov 15 '22 02:11

VGE