Is it possible to make a derived class uncovered by declaring a constructor instance / statement private in the base class?

I thought that theoretically the answer to this question was yes.

However, in practice, my compiler (VS2010) does not seem to complain in the following situation: I have an abstract base class that provides some common interface (yet has no data) and various sub and subclasses derived from it.

class Base { public: Base() {} virtual ~Base() {} virtual void interfaceFunction1() = 0; virtual void interfaceFunction2() = 0; private: Base(const Base&); // all derived classes should be uncopyable Base& operator=(const Base&); // no data members }; 

My compiler found that to implement full-text constructors in sub- or subtasks, it’s not even easy to implement full-copy constructors.

How can I make sure that every class derived from Base is not available?

edit: If I understand well, this is exactly what Scott Meyers explained in Section 6 of Effective C ++ (3rd edition, 2005) with his idea of ​​the Uncopyable class (only the full interface class extended here). What is the difference that makes it work? (I know that he inherits privately, but this should not be a problem)

+6
source share
2 answers

This should prevent the compiler from creating a copy constructor for derived classes that are not explicitly declared. However, there is nothing stopping the derived class from declaring a copy constructor explicitly, which will do something else besides invoking the Base copy constructor.

There is no way to ensure that derived classes are objective, but not copyable.

+3
source

Instead of declaring the constructor / copy statement as a private declaration, declare them deleted. Declaring the constructor / copy operator as private is not the best solution so that derived classes are not copied. If you want the base class not to be completely copied, declare the copy constructor / operator to delete d, since the copy can still be executed inside the member functions. The base as private members are available for these class functions. You can use the C ++ 11 function to remove:

 Base(const Base&) = delete; // copy constructor Base& operator=(const Base&) = delete; // copy-assignment operator 

But declaring the constructor / copy statement as private is also correct if you know that a copy can still be executed inside the Base member functions.

+1
source

All Articles