Search code examples
c++copy-constructorpimpl-idiom

How to call copy constructor of a caller class from pimpl class?


I just need to know if I want to call my copyconstuctor from pImpl class, how will I do it? For example:

CImpl::SomeFunc()
{

//cloning the caller class instance

caller = new Caller(*this)// I cant do this since its a pImpl class

}

How can i achieve this?


Solution

  • Well after reading your comments, it seems that you want to be able to provide the ability to make copies of Caller class. If so, then in that case you should implement the copy constructor for Caller class, where you can make a hard copy of m_pImpl pointer.

    class CallerImpl;
    
    class Caller
    {
       std::shared_ptr<CallerImpl> m_pImpl;
    public:
       Caller(Caller const & other) : m_pImpl(other.m_pImpl->Clone()) {}
       //...
    };
    

    And then you can implement Clone() function in CallerImpl class as:

    class CallerImpl
    {
       public:
         CallerImpl* Clone() const
         {
             return new CallerImpl(*this); //create a copy and return it
         }
         //...
    };
    

    Now you can make copy of Caller:

    //Usage
    Caller original;
    Caller copy(original);