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.
Yes you should. Rules of having your own implementations for copy constructor, copy assignment operator and destructor for a Class will apply to even an Abstract Class.
The default copy constructor makes a member-wise copy, and whether a deep or shallow copy is made of a member depends entirely on the behavior of members. struct Person { string firstName, lastName; } - the default copy constructor makes a deep copy.
In Deep copy, an object is created by copying data of all variables, and it also allocates similar memory resources with the same value to the object. In order to perform Deep copy, we need to explicitly define the copy constructor and assign dynamic memory as well, if required.
Shallow Copy stores the references of objects to the original memory address. Deep copy stores copies of the object's value. Shallow Copy reflects changes made to the new/copied object in the original object. Deep copy doesn't reflect changes made to the new/copied object in the original object.
Take a look at the virtual constructor idiom
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With