Search code examples
c++constructordefault

How to use " = default" with a constructor that has a body?


Suppose I have a class that has a couple of member variables. In the copy constructor for example I wanna copy all the members and do some more work. Instead of copying the member variables explicitly, how to tell the compiler to have the default behavior (copy the member variables) and also do what's in the body of the function?

Something like this:

class X
{
public:

    // This constructor should copy all the members
    // and also do what's inside the constructor's body.   
    X(const X& x) = default
    {
        // Do some work.
    }
};

Solution

  • That doesn't make much sense from a construction perspective as the job of a constructor is to set the member data, and nothing else.

    But if you require this pattern, perhaps for registering the object somehow for example, one solution though would be to have

    class Y : public X
    {
        Y(const Y&){
            // Do some work
        }
        // No member data here 
    };