Define all essential operations or none for a class

Hi all,

If we rely on the rule: Define all essential operations or none for a class, when are we to decide to use each? I mean, when must we define all 7 functions for our class, mostly? I've heard that we do that when there's a resource in the class that we grab in the constructor and release in the destructor. Is it right?

Thanks.
Last edited on
What are the 7 functions?
Five are: dtor, copy ctor, move ctor, copy assign, move assign.
What are the other two?
Last edited on
Default constructor
Normal constructor (with arguments for instance)
Copy constructor
Copy assignment
Move constructor
Move assignment
Destructor

The default ctor is a special one, that's true.
So that's six.
I don't know about non-default ctors ... maybe, but there can be more than one of them.

Do you have a reference for this "seven" rule?
#7 could be swap. I don't think non-default constructors need special consideration.
Last edited on
swap is a good one, although it's not built into the language syntax.

default ctor   Object();   (any params must have defaults)
dtor           ~Object();  (probably virtual if object is polymorphic)
copy ctor      Object(const Object&);
move ctor      Object(Object&&);
copy assign    Object& operator=(const Object&);
move assign    Object& operator=(Object&&);
swap           swap(Object& a, Object& b);


@frek, be sure to read the "rule of three/five" link salem.c posted above.
Another excellent page from that site: https://en.cppreference.com/w/cpp/language/operators
It shows how to make proper assignment operator overloads and also other standard overloads like input/output, increment/decrement and the comparison operators.
Last edited on
frek wrote:
I've heard that we do that when there's a resource in the class that we grab in the constructor and release in the destructor. Is it right?

Not just "Grabbing a resource", but grabbing it in a way that requires explicit action to release it. For example, if the resource is held in a member of non-class or otherwise non-raii type (here's another important link https://en.cppreference.com/w/cpp/language/raii ). It's that explicit action to release that means you have to write the destructor and therefore yes, define or delete the rest of them.

For a simple non-resource related example, a class that counts its instances by incrementing a global counter in constructor and decrementing in destructor. Or for something less dumb, a class that registers its instances in some global table in constructor and removes itself from it in destructor.
Topic archived. No new replies allowed.