You are here:

C++/Clone and encapsulation in c++

Advertisement


Question
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:

struct BASE
{
       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
}

See: http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8


---------- 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.

Answer
> 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:
http://idynsolutions.wordpress.com/2006/11/08/oop-concept-encapsulation/

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.