C++/Clone and encapsulation in c++
QUESTION: Hi, as i understand clone provides way of virtual constructor or copy constructor. I've read somewhere it helps encapsulation. How it does? Please explain how encapsulation and cloning in c++ related? Any help to understand the concept would be highly appreciated.
ANSWER: Cloning is the making another object which is an exact copy of a given object (instead of just copying a pointer or reference).
> Please explain how encapsulation and cloning in c++ related?
Let us say, we have a base class BASE at the root of an inheritance hierarchy and we need to make exact copies of objects belonging to this hierarchy:
virtual ~BASE() ;
// virtual ... = 0 ;
virtual BASE* clone() const = 0 ;
void some_function( BASE* ptr_object )
// we need to make an exact copy of the object pointed to by ptr_object
// we know that it is an object that belongs to some unknown class that is derived from BASE
// we have not seen any derived class of BASE, but we could still make a copy this way:
BASE* ptr_copy = ptr_object->clone() ;
// use the copy
---------- FOLLOW-UP ----------
QUESTION: Thanks alot for the answer provided by you. But my question still the same how come i am providing encapsulation.
Whether you are saying without knowing that pointer pointing to which object we are able to make copy of the object is providing us encapsulation. Whether this is object encapsulation? or may be i am not aware of what actually encapsulation is.
As per my understaing encapsulation hide the implementation details. So how are we achieving using cloning.
Kindly ignore if my question sound vague and to my limited knowledge.
Answer to this question would be appreciated.
> As per my understaing encapsulation hide the implementation details. So how are we achieving using cloning.
Polymorphic cloning is not a mechanism to achieve abstraction or encapsulation.
Cloning is a mechanism that uses abstraction and encapsulation to allow us to make a copy of an object without knowing anything about its implementation details.
Here is a brief explanation of encapsulation: