If the copy constructor is private or public

I am writing an abstract class that will be the parent for several other classes. I think that the copy constructor should be private, because you are using an abstract class and there is nothing to copy. However, I am not 100% sure.

Am I right and if I should not be public or protected?

+6
source share
3 answers

The copy constructor must be private if you do not want to copy class objects. Otherwise, it must be publicly available.

+8
source

I think that protected is the best choice: it leaves a decision on whether the object is copied for derived classes, prohibiting copying at the level of the abstract class, preventing a scary cut of objects .

+6
source

By closing the copy constructor, you will help prevent objects from being accidentally split when you make a copy of a derived class, but lose all the properties of that derived class. The resulting classes can create their own copy constructors, which are public and do the right thing.

In one case, when the copy constructor should be protected instead of the private one, when the abstract class has data members. This happens infrequently. A base class can copy elements of a base class, and a derived class copies its own members.

 class AbstractBase { public: AbstractBase(const std::string &init) : wtf(init) {} virtual ~AbstractBase() {} void DoSomething() = 0; protected: AbstractBase(const AbstractBase &r) : wtf(r.wtf) {} const std::string wtf; }; class Derived : public AbstractBase { public: // ... Derived(const Derived &r) : AbstractBase(r), moredata(r.moredata) {} private: int moredata; }; 
+3
source

Source: https://habr.com/ru/post/909199/


All Articles