Domanda

How inheriting a noncopyable class with a private copy constructor and an assignment operator is going to prohibit the use of copy constructor and assignment operator on the derived class? Please consider the following scenario while replying, individually,

  • What if, Default copy constructor and assignment operator are generated by the compiler in the derived class and not added by the programmer

  • What if, Copy constructor and assignment operator are defined and declared public in the derived class by the programmer

  • What if, Copy constructor and assignment operator are defined and declared private in the derived class by the programmer

È stato utile?

Soluzione 2

Default copy constructor and assignment operator are generated by the compiler in the derived class and not added by the programmer

The implicit functions will try to call their counterparts in the base class. This won't be possible since those are private to the base class, so you'll get a compilation error. This is how the base class is intended to work.

Copy constructor and assignment operator are defined and declared public in the derived class by the programmer

Then you've defeated the purpose of inheriting from the base class; your derived class is now copyable via these functions.

Copy constructor and assignment operator are defined and declared private in the derived class by the programmer

Again, you've defeated the base class and made your class copyable; but only within its member and friend functions.

Altri suggerimenti

1) Then any copy or assignment will fail to compile, because the compiler generated copy constructor and assignment operator requires access to those of the base class.

2) That would be a programmer error. You want your class to be non-copyable and non-assignable, so you shouldn't provide public methods to do so. The compiler could produce a warning, but the code would compile.

3) Then assignment and copying will result in compilation error as in 1) above, unless called by friend functions or classes, or internally in the same class.

The take-home message is that you should not provide copy constructor or assignment operator for a non-copyable class. Let the inheritance mechanism provide the necessary restrictions by itself.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top