I have the following error in my code:
error: allocating an object of abstract class type \'Material\'
I don\'t know how to handle this case.
You can use a templated constructor to arrange for constructing the right types without needing a clone method:
#include
#include
struct Material {
Material() = default;
virtual int get_color() const = 0;
};
struct Basic : Material {
Basic() = default;
int get_color() const override {
return 1;
}
};
struct Mix : Material {
template
Mix(const M1& mat1, const M2& mat2)
: mat1_{std::make_unique(std::move(mat1))}
, mat2_{std::make_unique(std::move(mat2))}
{}
int get_color() const override {
return mat1_->get_color() + mat2_->get_color();
}
private:
std::unique_ptr mat1_;
std::unique_ptr mat2_;
};
int main() {
auto mix = Mix(Basic(), Basic());
std::cout << mix.get_color() << '\n';
}
Note that this works only if you send instance of a material with a known type.