Copy constructor: deep copying an abstract class

2019-04-04 05:35发布

Suppose I have the following (simplified case):

class Color;

class IColor
{
public: 
    virtual Color getValue(const float u, const float v) const = 0;
};

class Color : public IColor
{
public:
    float r,g,b;
    Color(float ar, float ag, float ab) : r(ar), g(ag), b(ab) {}
    Color getValue(const float u, const float v) const 
    { 
        return Color(r, g, b)
    }
}

class Material
{
private:
    IColor* _color;
public:
    Material();
    Material(const Material& m);
}

Now, is there any way for me to do a deep copy of the abstract IColor in the copy constructor of Material? That is, I want the values of whatever m._color might be (a Color, a Texture) to be copied, not just the pointer to the IColor.

4条回答
仙女界的扛把子
2楼-- · 2019-04-04 05:42

You'll have to add that code yourself to the Material copy constructor. Then code to free the allocated IColor in your destructor.

You'll also want to add a virtual destructor to IColor.

The only way to do a deep copy automatically would be to store a color directly instead of a pointer to an IColor.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-04 05:44

Adding a clone() method to color is probably best, but if you don't have that option, another solution would be to use dynamic_cast to cast IColor* to Color*. Then you can invoke the Color copy constructor.

查看更多
甜甜的少女心
4楼-- · 2019-04-04 06:02
干净又极端
5楼-- · 2019-04-04 06:04

You could add a clone() function to your interface.

查看更多
登录 后发表回答