0

I want to publicly hide the copy constructor and the assignment operator.

Furthermore i want to provide a clone().

Is it possible to just mark the copy constructor and the assignment operator as protected or private and use them in the clone function?

Maybe some kind of using clause.

The reason is that the class contains some data and a unique id that should be incremented with every instance. So making a copy would be using the default assignment operator and then change the id. I would like to circumvent the need to copy every member by hand to avoid forgetting to add one if a member was added to class.

vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80

3 Answers3

3

You can do:

class MyClass {
      MyClass(const MyClass&) = default;
      MyClass& operator=(const MyClass&) = default;
};
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

Since the answer of πάντα ῥεῖ would be the most favorable if c++11 is available I solved the problem by using a CRTP object counter that manages the id.

This class implements the counter and re-implements the copy c'tor and assignment operator so that the default ones of the child class can be created and used without danger.

template <class T>
class UidProvider
{
public:
  UidProvider()
  {m_id = getNewUId();}

  UidProvider(const UidProvider&)
  {m_id = getNewUId();}

  UidProvider& operator= (const UidProvider&)
  {m_id = getNewUId();}

  uint32 id()
  {return m_id;}

private:
  uint32 m_id;

  static uint32 getNewUId(){ return ++sm_id;}
  static uint32 sm_id;
};

class MyClass : public UidProvider<MyClass >{
 // ...
}

// in cpp
uint32 UidProvider<MyClass >::sm_id = 0;
IInspectable
  • 46,945
  • 8
  • 85
  • 181
vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80
0

hide auto generated assignement operator and copy constructor without replacing them

To be pedantic, not possible.

In c++03 absolutely not possible.

In c++11, defining them as =default is technically providing a user-defined assignment operator and copy constructor, it's just that you're replacing them with the same functions that the compiler would implicitly generate. This will have the same effects as writing them explicitly - i.e. preventing the auto-generation of a move-assignment and a move-constructor.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142