Special Member Functions - Example

Example

The following example depicts two classes: Explicit for which all C++98 special member functions are explicitly declared and Implicit for which none are declared.

#include class Explicit { friend class Implicit; string msg; public: Explicit : msg("") { std::cout << "Default constructor " << msg << '\n'; } Explicit(const string& value) : msg(value) { std::cout << "Non-default constructor " << msg << '\n'; } Explicit(const Explicit& other) : msg(other.msg) { std::cout << "Copy constructor " << msg << '\n'; } Explicit& operator=(const Explicit& other) { std::cout << "Copy assignment operator " << msg << '\n'; if (this != &other) { msg = other.msg; } return *this; } ~Explicit { std::cout << "Destructor " << msg << '\n'; } }; class Implicit : public Explicit { int i; void* p; Explicit member; public: void Spew { std::cout << "Implicit(" << msg << ", " << member.msg << ")\n"; } };

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 }

Read more about this topic:  Special Member Functions

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)