Can I force a derived class to define a copy/move operator/constructor?

Hi.

I want to force a derived class to define user defined copy constructor/assignment operator, and move too.

It will be good if acting like a pure virtual function.

Is there any way?


I don't think that there is a way.
Why do you want to do it? It would make the class much more difficult to use.
you could make your base class non-copiable/assignable/movable, then the derived classes would need to implement custom copy/assign/move constructor
to do that, either delete them or declare them private.

> It will be good if acting like a pure virtual function.
no sure if I understood you
1
2
3
4
5
6
class vehicle;
class car: public vehicle;
class bicycle: public vehicle;

bicycle b; car c;
b = c; //¿what do you expect to happen here? 
@ne555,
not sure if I understand you correctly. Even if you delete the copy and assignment ctors and operators you could still create a derived class without implementing these.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

class Useless
{
public:
  Useless(){}
private:
  Useless(const Useless&) = delete;
  Useless(Useless&&) = delete;

  Useless& operator=(const Useless&) = delete;
  Useless& operator=(Useless&&) = delete;
};

class Derived: public Useless
{
public:
  Derived(): Useless()
  {
    std::cout << "Derived ctor";
  }
};

int main()
{
  Derived d;
}

Output:
Derived ctor
@thmm:
Derived e = d; generates:
 In function 'int main()':
27:15: error: use of deleted function 'Derived::Derived(const Derived&)'
15:7: note: 'Derived::Derived(const Derived&)' is implicitly deleted because the default definition would be ill-formed:
8:3: error: 'Useless::Useless(const Useless&)' is private
15:7: error: within this context
15:7: error: use of deleted function 'Useless::Useless(const Useless&)'
8:3: note: declared here

The point is that you can't copy or move Derived trivially.

Compiler can generate implicit copy/move for derived classes.
If that does the "right thing", then why should we have to write explicit constructors/assignments?

If the implicit implementation is not appropriate for a class, then the programmer should write explicit version.
However, there is no way for the author of base class to know whether the derived class will have such need.
The point is that you can't copy or move Derived trivially.

@keskiverto,
that I understand. You still could use Derived without copy or move, so it's not really enforced.
Maybe the OP tells us the reason behind, somehow I can't see a real use for it.
Topic archived. No new replies allowed.