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, but not declared explicitly by the programmer. The special member functions are:
- Default constructor (if no other constructor is explicitly declared)
- Copy constructor
- Copy assignment operator
- Destructor
In these cases the compiler generated versions of these functions perform a memberwise operation. For example the compiler generated destructor will destroy each sub-object (base class or member) of the object.
[edit] Example
The following example depicts two classes: Explicit for which all special member functions are explicitly declared and Implicit for which none are declared.
class Explicit { friend class Implicit; string msg; public: Explicit(void) : msg("") { cout << "Default constructor " << msg << endl; } Explicit(const string& value) : msg(value) { cout << "Non-default constructor " << msg << endl; } Explicit(const Explicit& other) : msg(other.msg) { cout << "Copy constructor " << msg << endl; } Explicit& operator=(const Explicit& other) { cout << "Copy assignment operator " << msg << endl; if (this != &other) { msg = other.msg; } return *this; } ~Explicit(void) { cout << "Destructor " << msg << endl; } }; class Implicit : public Explicit { int i; void* p; Explicit member; public: void Spew(void) { cout << "Implicit(" << msg << ", " << member.msg << ")" << endl; }; };
In this case the class Implicit 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 Implicit::~Implicit() { member.~Explicit(); // destroy member (void)p; // do nothing for p, void* has no destructor (void)i; // do nothing for i, int has no destructor ~Explicit(); // call the base class's destructor }