liveBook · Manning

Special member function

As explained in Learn C++ by Example

A special member function is one of the compiler-recognized constructors, destructor, copy operations, or move operations that govern object initialization, copying, moving, and destruction.

Special member functions are six compiler-recognized operations governing default construction, copying, moving, assignment, and destruction: the default constructor, copy constructor, copy assignment, move constructor, move assignment, and destructor. Leaving them undeclared invokes the rule of zero, which often avoids unnecessary code and bugs. section 6.1.1 section 6.1.4

The six operations are:

Inheritance changes the practical rules. A polymorphic base class should declare a virtual destructor so deleting a derived object through a base pointer destroys it correctly. A user-declared destructor can prevent implicit move operations; classes needing move semantics may therefore follow the rule of five and declare all five relevant operations. section 6.1.1 section 6.3

A base class with deliberate special members

A race base class can default its constructor and virtual destructor while deleting copying. Its pure virtual methods make it abstract, and derived blobs supply the behavior. Type traits can then verify that the class is destructible but not default-constructible, copyable, or movable. section 6.1.1 section 6.1.4

Listing 6.2 A better base class
#pragma once
 
namespace Race
{
    class Blob
    {
    public:
        virtual ~Blob() = default;                #1
        Blob() = default;                         #2
        Blob(Blob const&) = delete;               #3
        Blob& operator=(Blob const&) = delete;    #3
 
        virtual void step() = 0;
        virtual int total_steps() const = 0;
    };
}

Inspect the base-class declaration showing a defaulted virtual destructor, default constructor, and deleted copy operations. section 6.1.1

How Learn C++ by Example covers it

How deep it goes
Defines all six operations, explains rules of zero, three, and five, and checks availability with type traits.
Examples
Demonstrates a Blob race hierarchy, deleted copy operations, virtual destruction, compile-time assertions, and default-constructible card types.
What you can do after
Evaluate special-member availability with std::is_* type traits and design polymorphic bases with appropriate defaulted or deleted operations.
How it connects
Connects constructors, destructors, copy and move semantics, inheritance, virtual functions, type traits, smart pointers, and vector insertion.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.