2

let's say I have a class named File. I want to disable the copy constructor for every son of File, for example TextFile.

Would doing something like this will still disable the copy constructor of TextFile?

class File {
public:
    File(const File& f) = delete;
};

class TextFile:public File {
public:
};

Or is this necessary in order for this to be disabled?

class File {
public:
    File(const File& f) = delete;
};

class TextFile:public File {
public:
    TextFile(const TextFile& tf) = delete;
};
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
איתן לוי
  • 433
  • 1
  • 3
  • 9
  • Possible duplicate of [Deleting copy constructor breaks inherited constructors](https://stackoverflow.com/questions/32954730/deleting-copy-constructor-breaks-inherited-constructors) – wally Sep 18 '19 at 12:55
  • Realted/duplicate: https://stackoverflow.com/questions/55007528/is-deleting-copy-and-move-constructors-assignment-operators-in-base-class-enough – StoryTeller - Unslander Monica Sep 18 '19 at 12:56
  • Possible duplicate of [Is deleting copy and move constructors/assignment operators in base class enough?](https://stackoverflow.com/questions/55007528/is-deleting-copy-and-move-constructors-assignment-operators-in-base-class-enough) – ead Sep 20 '19 at 21:40

2 Answers2

4

Your first code block is all you need. Since File is not copyable when the compiler goes to generate the copy constructor for TextFile it will see that and implicitly delete it since it can't make a legal copy constructor.

What it does not do though is to stop you from making your own copy constructor in the derived class. If you are okay with that then that is all you need.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
2

The copy constructor of the derived class is also implicitly deleted in the first code snippet.

From the C++ 17 Standard (15.8.1 Copy/move constructors)

10 An implicitly-declared copy/move constructor is an inline public member of its class. A defaulted copy/move constructor for a class X is defined as deleted (11.4.3) if X has:

(10.1) — a potentially constructed subobject type M (or array thereof) that cannot be copied/moved because overload resolution (16.3), as applied to find M’s corresponding constructor, results in an ambiguity or a function that is deleted or inaccessible from the defaulted constructor,

But for self-documentation of your code you can explicitly specify in derived classes that the copy constructor is deleted.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335