Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor: deep copying an abstract class

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.

like image 541
erik Avatar asked Sep 28 '09 14:09

erik


People also ask

Can we make copy constructor in abstract class?

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.

Does a copy constructor make a deep copy?

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.

What is deep copy constructor?

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.

What is the difference between shallow copy and Deepcopy in C++?

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.


1 Answers

Take a look at the virtual constructor idiom

like image 50
Nemanja Trifunovic Avatar answered Sep 29 '22 22:09

Nemanja Trifunovic