4

Pre C++11, I asked whether this was possible using the private/not-implemented trick (see here). Apparently, this was not possible.

I wonder whether the new = delete syntax has changed the state of affairs, as forcing derived classes to be uncopyable would still be a useful feature.

The updated code snippet could look something along these lines:

class Base 
{
public:
    Base() {}
    virtual ~Base() {}
    Base(const Base&) = delete;
    Base& operator=(const Base&) = delete;

    virtual void interfaceFunction() = 0;
    // etc.

    // no data members
};

class Data { /* ... */ };
class Derived : public Base  // is this class uncopyable ?
{
    Derived() : managedData(new Data()) { }
    ~Derived() ( delete managedData; }

    virtual void interfaceFunction() override { /* ... */ }

    Data* managedData; 
};
Community
  • 1
  • 1
mr_T
  • 2,571
  • 3
  • 22
  • 39
  • Can I ask why you want a base class that forces the derived class to be uncopyable? Is it to prevent mishandling of the managed data you have now shown in your derived class? This data looks like it should be held by a `unique_ptr`. – Chris Drew Jun 03 '16 at 08:31
  • The base class (a kind of implementation/calculation class) is indeed owned through an unique_ptr by another class. Other developers can write their own derived class but should respect the design of a non-copyable class. – mr_T Jun 07 '16 at 11:13

1 Answers1

5

No, the derived class is free to construct Base in its copy constructor/assignment operator as it wishes.

class Derived : public Base {
public:
    Derived(){}
    Derived(const Derived&) : Base() {}
    void interfaceFunction() override {}
};
Chris Drew
  • 14,926
  • 3
  • 34
  • 54
  • 2
    Easy work around: delete *all* constructors for `Base`. Now any `Derived` type cannot copy `Base`! (no guarantee that the `Derived` class can be created at all is provided) – Yakk - Adam Nevraumont Jun 02 '16 at 15:40