Special member functions

From Wikipedia, the free encyclopedia

Special member functions[1] in C++ are functions which the compiler will automatically generate if they are used and no explicit definition is supplied. The special member functions are:

In these cases the compiler generated versions of these functions performs a memberwise operation. For example the compiler generated destructor will destroy each sub-object (base class or member) of the object.

[edit] Example

class greeter {
    string msg;
public:
    greeter(const string& message)
        : msg(message) 
    {
        cout << "Hello " << msg << endl;
    }

    ~greeter()
    {
        cout << "Goodbye " << msg << endl;
    }
};

class example : public greeter {
    int i;
    void* p;
    greeter member;
public:
    example() 
        : greeter("base class") // Call the base class's constructor
        , i(42)
        , p(this)
        , member("member")
    {}
}; 

In this case the class example has not explicitly defined the destructor and the compiler will create a destructor equivalently to this:

// Sub-objects are destroyed in the opposite order to their construction
example::~example()
{
    member.~greeter(); // destroy member
    (void)p;           // do nothing for p, void* has no destructor
    (void)i;           // do nothing for i, int has no destructor
    ~greeter();        // call the base class's destructor

}

[edit] References

  1. ^ C++ standard (ISO/IEC14882) section 12.