Is there a way to declare Copy Constructor non-public and use the default Copy Constructor?

I have a not very small class in development (which it changes frequently) and I don't need to provide a public copy constructor and copy assignment. The class has objects with semantic values, so the default copy and assignment is done.

the class is in a hierarchy with virtual methods, so I provide a virtual Clone () to avoid slicing and perform a "polymorphic copy".

I don't want to declare copy assignment and protected construct AND define them (and keep in sync with changes) unless I have some special thing to do.

Does anyone know if there is another way?

thank!

UgaSofT

0


source to share


4 answers


Object from polymorphic hierarchy and value semantics? Something is wrong here.

If you really need your class to have value semantics take a look at J. Coplien Envelop-Letter Idiom or this article on Regular Objects [1].



[1] Sean Parent. "Beyond Objects". Understanding the software we write. http://stlab.adobe.com/wiki/index.php/Papers_and_Presentations . C ++ links. 2005 November

NTN,

+3


source


I don't think there is anything in C ++ that allows you to do this. Although I would like to be mistaken on this issue.

I've encountered this in the past and came up with the following solution. The Asumme class is C1.

  • Define a private inner class named Data li>
  • Put all my members, I would like to share in C1 to Data instead
  • Define a protected copy constructor that simply copies data instances between C1.


This approach has several disadvantages. Namely, it feels a bit unnatural and removes direct field access (can be mitigated with small accessor functions).

It's a roundabout way of doing what you're looking for, but it allows you to write a written constructor by hand.

0


source


I may have found a solution ...

I can put in my base class root (or I can create a small interface class, no data items, and do multiple inheritance) a protected copy constructor, which is empty here. I do not override Copy ctor in derived classes when it is okay by default. Now the copy of the ctor is not available to clients by default (because the base is not available), but it works by default!

Are there any objections?

0


source


If you can use C ++ 0x ...

class A
{
    protected:
        A(const A&) = default;
};

      

0


source







All Articles