Copy constructor: deep copying an abstract class

2019-04-04 05:15发布

问题:

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.

回答1:

Take a look at the virtual constructor idiom



回答2:

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



回答3:

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.



回答4:

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.